[英]P/Invoke Marshalling an Out void*
I have the following C function definition: 我有以下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;
}
The function is called via P/Invoke. 通过P / Invoke调用该功能。 The P/Invoke function definition is as follows:
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);
The usage of this function is: 此功能的用法是:
IntPtr windowHandle;
bool windowCreationSuccess = _CreateWindow(Engine.ApplicationTitle, out windowHandle);
My problem is that windowHandle
is always equal to IntPtr.Zero in the C# code, which I guess means that it isn't being 'copied' from the C++ to C# side somehow. 我的问题是
windowHandle
总是在C#代码,我想意味着它不被“复制”从C ++到C#侧不知何故等于IntPtr.Zero。 It is being set in the C function (I looked with the debugger)- it is actually a HWND. 它是在C函数中设置的(我在调试器中查看过),它实际上是HWND。
P/Invoke never ceases to confuse me - I'm sure I've done something wrong with copying a struct rather than a reference to it or something, but I can't quite see what/where. P / Invoke永远不会使我感到困惑-我确定复制结构而不是引用结构或某些东西时我做错了事,但是我看不到在哪里。
C uses pass by value exclusively. C专门使用按值传递。 This means that your assignment to
windowHandle
can never be seen by the caller. 这意味着调用者将无法看到您对
windowHandle
的分配。 That is so for any caller, not just a managed pinvoke. 对于任何呼叫者而言都是如此,而不仅仅是托管的pinvoke。
You need to change the C function to receive the address of the window handle variable. 您需要更改C函数以接收窗口句柄变量的地址。 Like this:
像这样:
EXPORT CreateWindow(const wchar_t* applicationTitle, HWND* windowHandle) {
// Some preconditions & other stuff here
*windowHandle = RENDER_COMPONENT.Window.CreateNew(cstr_to_wstring(applicationTitle));
return true;
}
The C# code in the question then matches. 然后,问题中的C#代码匹配。
However your C code is odd. 但是,您的C代码很奇怪。 Why do you return true unconditionally?
为什么您无条件返回true? Why bother returning a bool if it is always true.
如果总是如此,为什么还要麻烦返回布尔。 Frankly it would be cleaner to return the HWND.
坦白说,返回HWND会更清洁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.