簡體   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