2016-11-18 173 views
0

我正在導入我的C#代碼中的非託管dll。 .h文件描述如圖所示波紋管c#中的管理非託管變量

DLL_API int __stdcall SetConfiguration(IN char* configuration); 

DLL_API int __stdcall GetErrorMessage_UTF16(
    INOUT int* errorGroup, 
    INOUT char* errorCode, /*It must be allocated by the caller and its length must be at least 10 bytes, otherwise the function will crash*/ 
    INOUT wchar_t *messageText, 
    IN int bufferLength); 

我已經成功地調用SetConfiguration方法

[DllImport(DllPath, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)] 
private static extern int SetConfiguration([In] MarshalAs(UnmanagedType.LPStr)] string configuration); 

供應一個簡單的C#字符串做了工作方法。

現在我正在嘗試GetErrorMessage_UTF16方法沒有成功。那麼,我該如何分配errorCode的長度,以及如何聲明wchar_t * messageText變量?

我已經試過這樣的事情,但它似乎沒有工作

[DllImport(DllPath, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)] 
private static extern int GetErrorMessage_UTF16(
    [In, Out] int errorGroup, 
    [In, Out] [MarshalAs(UnmanagedType.LPStr)] string errorCode, 
    [In, Out] [MarshalAs(UnmanagedType.LPStr)] StringBuilder messageText, 
    [In] int bufferLength); 

不管我試過我得到

Exception thrown at 0x0f5d1235 (Mydll.dll) in Mydll.exe: 0xc0000005: Access violation writing location 0x067d1000 

If there is a handler for this exception, the program may be safely continued. 
+0

第一個arg應該是'out int',第二個arg看起來應該是StringBuilder,第三個arg是LPWStr –

回答

1

OK,我已經找到了答案

[DllImport(DllName, EntryPoint = "GetErrorMessage_UTF16", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)] 
public static extern int GetErrorMessage_UTF16(out int errorGroup, IntPtr errorCode, IntPtr messageText, int bufferLength); 

對於errorCode和messageText創建一個指針,然後分配大小。

IntPtr errorCode = Marshal.AllocHGlobal(10); 
IntPtr messageText = Marshal.AllocHGlobal(someBufferLength * sizeof(char)); 

當不需要變量時,不要忘記釋放分配的空間。