C# 无法封送';返回值';:无效的托管/非托管类型组合
我在非托管库中有这个函数,我想在C#中调用它:C# 无法封送';返回值';:无效的托管/非托管类型组合,c#,c++,marshalling,C#,C++,Marshalling,我在非托管库中有这个函数,我想在C#中调用它: unsigned char\uu stdcall InitDev(unsigned char comport,长波特率) 这是C语言# 但是当我在C#中调用这个函数时,我得到了以下错误 无法封送“返回值”:无效的托管/非托管类型组合 我是新手,如果提供一点指导,我将能够解决这个问题 假设您的本机调用类似于unsigned char*InitDef(unsigned char*,long-long&baudRate)那么您可能希望使用IntPtr来代
unsigned char\uu stdcall InitDev(unsigned char comport,长波特率)
这是C语言#
但是当我在C#中调用这个函数时,我得到了以下错误
无法封送“返回值”:无效的托管/非托管类型组合
我是新手,如果提供一点指导,我将能够解决这个问题
假设您的本机调用类似于
unsigned char*InitDef(unsigned char*,long-long&baudRate)
那么您可能希望使用IntPtr
来代替unsigned char*
。但首先,由于它是托管/非托管混合,您应该为输入和输出分配字节[]
缓冲区:
byte[] pInBuffer = Encoding.ASCII.GetBytes("COM3");
// allocate unmanaged memory
IntPtr inputBuffer = Marshal.AllocHGlobal(pInBuffer.Length * sizeof(byte));
Marshal.Copy(pInBuffer, 0, inputBuffer, pInBuffer.Length);
// now your inputBuffer contains a native pointer to the `unsigned char*`
// and since your function returns a new pointer to some `unsigned char*`
// just retrieve it to IntPtr
IntPtr result = InitDev(inputBuffer, 9600);
// free your allocated memory
Marshal.FreeHGlobal(inputBuffer);
在此阶段,您的结果
包含从InitDev
返回的值
InitDev
函数的新定义
所有必要的电话,你都可以在这里找到
编辑:
由于本机调用如下所示:
extern unsigned char\uu stdcall InitDev(unsigned char comport,long BaudRate)代码>
我猜第一个参数只是的“COMn”
的最后一个数字(索引),因为无符号字符的最低可能值是0,而COM的最低索引可以是0
尝试使用以下代码段:
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("*.dll", CallingConvention = CallingConvention.Cdecl,CharSet =CharSet.Auto)]
public static extern byte InitDev(byte comport, long BaudRate);
然后这样称呼它:
byte comIdx = 3;
byte result = InitDev(comIdx, 9600);
// byte should yield correct result now
附加信息:调用PInvoke函数“WindowsFormsApplication1!”!WindowsFormsApplication1.Form1::InitDev'已使堆栈不平衡。这可能是因为托管PInvoke签名与非托管目标签名不匹配。检查PInvoke签名的调用约定和参数是否与目标非托管签名匹配。您能否准确地发布InitDev
的定义在native.h文件中的外观?我已经获得了此设备的SDK,它有此头文件,但没有以适当的方式进行解释。。。让我向您展示它:unsigned char\uu stdcall InitDev(unsigned char comport,long BaudRate);C#与无符号字符
的等价物是字节
,因此,您只需使用字节
而不是字节[]
或IntPtr
。我会在一秒钟内编辑它。这个函数在C程序中几乎不可能可靠地调用,当你从C#中调用它时,它会变得更好。您不知道数组中有多少个元素,也不知道如何释放它。您必须与该代码的程序员交谈,以了解该指针的含义。只要你这么做,就让他来修理。波特率参数是一个整数。
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("*.dll", CallingConvention = CallingConvention.Cdecl,CharSet =CharSet.Auto)]
public static extern IntPtr InitDev(IntPtr comport, [Out] long BaudRate);
[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("*.dll", CallingConvention = CallingConvention.Cdecl,CharSet =CharSet.Auto)]
public static extern byte InitDev(byte comport, long BaudRate);
byte comIdx = 3;
byte result = InitDev(comIdx, 9600);
// byte should yield correct result now