开发者

Defining a C++ type in C#

开发者 https://www.devze.com 2022-12-19 07:47 出处:网络
I have a .DLL and a .h file. I\'m using c#, but the .DLL is written in C++. I have to problem with calling certain function within the .DLL. The problem comes when I need to call functions that have t

I have a .DLL and a .h file. I'm using c#, but the .DLL is written in C++. I have to problem with calling certain function within the .DLL. The problem comes when I need to call functions that have types defined in them . For example include with the .DLL was a .h file and it has a type defined like follows:

struct device_info {
  HANDLE dev_handle;  // valid open handle or NULL
  wchar_t* product_string;     // malloc'd string or NULL
  wchar_t* serial_string;     // malloc'd string or NULL
};
typedef struct device_info *PDEV_INFO;

I tried to run with it and created a structure like so:

[StructLayout(LayoutKind.Sequential)] public struct PDEV_INFO
{
        unsafe void* dev_handle;
        unsafe char* product_string;
        unsafe char* serial_string;

}

My program just crashes I try to use any of those types. How would I define these types 开发者_Python百科in C# or how can I reference types from a .h file? Even better would be the types defined somewhere in the .DLL and I'm just unaware. Thanks.


Try IntPtr instead of pointers. IntPtr was designed for Marshalling, c# pointer weren't. Also, you might want to read up on string marshalling. You really don't need to do that yourself.

Try declaring your type as:

[StructLayout(LayoutKind.Sequential)] 
public struct PDEV_INFO
{
        IntPtr dev_handle;
        [MarshalAs(UnmanagedType.LPWStr)] 
        String product_string;
        [MarshalAs(UnmanagedType.LPWStr)] 
        String serial_string;

}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号