C#互操作服务-使用C dll-void*

本文关键字:dll-void 使用 互操作 服务 | 更新日期: 2023-09-27 18:28:05

我在与用C编写的DLL进行互操作时遇到了问题。我不确定用什么类型的参数来代替void*

这就是给定DLL的API的样子:

POSNET_API POSNET_STATUS __stdcall POS_SetDeviceParam  ( POSNET_HANDLE  hDevice,  
    unsigned long  paramCode,  
    void *  paramValue   
) 

这就是我试图在C#中导入它的方式:

[DllImport(EXT_DLL)]
private static extern int POS_SetDeviceParam(IntPtr hDevice, int POSNET_DEV_PARAM_IP, *type* paramValue);

代替了我放的类型:

[MarshalAs(UnmanagedType.LPStr)] string and other L*Str
[MarshalAs(UnmanagedType.LPArray)] char[] and other type of arrays including of type byte
IntPtr which where AllocHGlobal, GCHandle.Alloc allocated before
even preceeding the method with unsafe and type = void*, combining above alloc aso.
raw type: string, char[]...

我一个人用尽了一切可能。

paramValue应该有一个IP值,格式如下:"192.168.1.1"-这就是它在C演示中的样子:

string ip="10.33.44.6";
POS_SetDeviceParam(hDevice,POSNET_DEV_PARAM_IP,(void*)ip.c_str());

在C#代码中,hDevice未初始化-POS_SetDeviceParam应使用其他参数对其进行初始化。欢迎提出任何建议!

C#互操作服务-使用C dll-void*

您将需要使用此p/Invoke签名:

[DllImport(EXT_DLL)]
private static extern int POS_SetDeviceParam(
    IntPtr hDevice, 
    int paramCode, 
    IntPtr paramValue
);

但是,您必须对该字符串执行一些操作,以便将其传递给IntPtr paramValue参数。

也许你可以尝试使用Marshal.StringToHGlobalAnsi(),因为这会给你一个可以使用的IntPtr。如果使用这种方法,请确保在完成后释放内存。

感谢大家的建议,下面的代码解决了我的问题!

[DllImport(EXT_DLL)]
private static extern int POS_SetDeviceParam(IntPtr hDevice, UInt32 POSNET_DEV_PARAM_IP, IntPtr paramValue);
void Test() {
     POS_SetDeviceParam(new IntPtr(), 0x00020005, Marshal.StringToHGlobalAnsi("192.168.1.1"));
}