【发布时间】:2014-05-26 18:32:18
【问题描述】:
我有以下 C 函数定义:
EXPORT CreateWindow(const wchar_t* applicationTitle, void* windowHandle) {
// Some preconditions & other stuff here
windowHandle = RENDER_COMPONENT.Window.CreateNew(cstr_to_wstring(applicationTitle));
return true;
}
该函数通过 P/Invoke 调用。 P/Invoke函数定义如下:
[DllImport(InteropUtils.RUNTIME_DLL, EntryPoint = "CreateWindow", CallingConvention = CallingConvention.Cdecl)]
internal static extern bool _CreateWindow([MarshalAs(UnmanagedType.LPWStr)] string applicationTitle, [Out] out IntPtr windowHandle);
这个函数的用法是:
IntPtr windowHandle;
bool windowCreationSuccess = _CreateWindow(Engine.ApplicationTitle, out windowHandle);
我的问题是 windowHandle 在 C# 代码中始终等于 IntPtr.Zero,我猜这意味着它不会以某种方式从 C++ 到 C# 端“复制”。它是在 C 函数中设置的(我用调试器查看过)——它实际上是一个 HWND。
P/Invoke 总是让我感到困惑 - 我确定我在复制结构而不是对它的引用或其他什么方面做错了,但我不太清楚什么/在哪里。
【问题讨论】:
-
这与 user32 中的 CreateWindowEx 方法完全不同吗? pinvoke.net/default.aspx/user32/CreateWindowEx.html
-
C 代码已损坏,当您从 C 程序调用它时,它也无法正常工作。正确的参数声明是
HWND*,比void**更漂亮。在尝试 pinvoke 之前,始终对 C 代码进行单元测试。