簡體   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