繁体   English   中英

无法封送“返回值”:无效的托管/非托管类型组合

[英]Cannot marshal 'return value': Invalid managed/unmanaged type combination

我在非托管库中有此功能,我想在C#中调用它:

unsigned char __stdcall InitDev(unsigned char comport, long BaudRate)

这是在C#中

[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("*.dll", CallingConvention = CallingConvention.Cdecl,CharSet =CharSet.Auto)]
public static extern byte[] InitDev(byte[] comport, [Out]long BaudRate);

但是当我在C#中调用此函数时,出现以下错误

“无法封送'返回值':无效的托管/非托管类型组合。”

string COM = "COM3";
byte[] ptr = new byte[1];
try
{
    ptr = InitDev(Encoding.ASCII.GetBytes(COM), 9600);
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

如果您提供一些指导,我对此是陌生的,我将能够解决此问题

在此处输入图片说明

假设您的本地调用类似于unsigned char* InitDef(unsigned char*, long long &baudRate)那么您可能想使用IntPtr代替unsigned char* 但是首先,由于它是托管/非托管混合,因此您应该为输入和输出分配该byte[]缓冲区:

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);

在此阶段,您的result包含InitDev返回的值。


InitDev函数的新定义

[System.Security.SuppressUnmanagedCodeSecurity]
[DllImport("*.dll", CallingConvention = CallingConvention.Cdecl,CharSet =CharSet.Auto)]
public static extern IntPtr InitDev(IntPtr comport, [Out] long BaudRate);

所有必要的调用,您都可以在此msdn页面上找到


编辑:
由于您的本地调用看起来像这样: extern unsigned char __stdcall InitDev(unsigned char comport,long BaudRate);
我猜第一个参数只是"COMn"的最后一位数字(索引),因为unsigned char的最低可能值为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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM