繁体   English   中英

P /调用编组出无效*

[英]P/Invoke Marshalling an Out void*

我有以下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#代码,我想意味着它不被“复制”从C ++到C#侧不知何故等于IntPtr.Zero。 它是在C函数中设置的(我在调试器中查看过),它实际上是HWND。

P / Invoke永远不会使我感到困惑-我确定复制结构而不是引用结构或某些东西时我做错了事,但是我看不到在哪里。

C专门使用按值传递。 这意味着调用者将无法看到您对windowHandle的分配。 对于任何呼叫者而言都是如此,而不仅仅是托管的pinvoke。

您需要更改C函数以接收窗口句柄变量的地址。 像这样:

EXPORT CreateWindow(const wchar_t* applicationTitle, HWND* windowHandle) {
    // Some preconditions & other stuff here
    *windowHandle = RENDER_COMPONENT.Window.CreateNew(cstr_to_wstring(applicationTitle));
    return true;
}

然后,问题中的C#代码匹配。

但是,您的C代码很奇怪。 为什么您无条件返回true? 如果总是如此,为什么还要麻烦返回布尔。 坦白说,返回HWND会更清洁。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM