从C#调用C / C ++ dll函数

时间:2013-05-14 19:41:02

标签: c# c++ dllimport

我试图在C#程序中从已编译的C / C ++ dll中调用一些函数。我已经成功调用了几个函数,但是遇到了几个函数。

Compliled c / c ++函数调用:

DECLDIR int ADS1292R_Get_Version(unsigned char ADS129x_Version[])
{
unsigned char Wbuf[10];
unsigned char Rbuf[10], RetVal =1;
Wbuf[0] = START_DATA_HEADER;                // PACKET Start header
Wbuf[1] = FIRMWARE_VERSION_REQ;             // Get firmware version info command
Wbuf[2] = 0x00;                             // Not used
Wbuf[3] = 0x00;                             // Not used
Wbuf[4] = 0x00;                             // Not used
Wbuf[5] = END_DATA_HEADER;                  // Packet End header
Wbuf[6] = '\n';


pComPort->Write(Wbuf, 7);                   // Send command to firmware
Sleep(5);
memset(Rbuf,0,7);
pComPort->Read(Rbuf, 7);                    // Receive response from Frimwate

if ((Rbuf[0] == START_DATA_HEADER) 
    && (Rbuf[1] == FIRMWARE_VERSION_PACKET) 
    && (Rbuf[5] == END_DATA_HEADER))
{
    ADS129x_Version[0]= Rbuf[2];            // Get Major Number
    ADS129x_Version[1]= Rbuf[3];            // Get Minor number
    RetVal = 0;                             // Set return val as su
}

return RetVal;

}

C#实现(以及该类的包装函数):

  [DllImport("ADS1292R_USB_lib.dll", EntryPoint = "ADS1292R_Get_Version")]
    public static extern int ADS1292R_Get_Version(byte[] x);

    public int getVersion()
    {
        byte[] dataTemp = new byte[3];
        int mydata = ADS1292R_Get_Version(dataTemp);
        if (mydata == 0)
        {
            MessageBox.Show("1:" + dataTemp[0].ToString() 
                            + " 2:" + dataTemp[1].ToString() 
                            + " 3:" + dataTemp[2].ToString());
        }
        return 0;
    }

在运行时,会出现以下错误。 有什么东西我不见了吗?

更新了错误文字:

“检测到PInvokeStackImbalance” “调用PInvoke函数'DLLTalk!DLLTalk.DLLClass :: ADS1292R_Get_Version'使堆栈失衡。这很可能是因为托管PInvoke签名与非托管目标签名不匹配。请检查PInvoke签名的调用约定和参数是否匹配目标非托管签名。“

1 个答案:

答案 0 :(得分:1)

不要忘记CallingConvention属性设置。此外,最好表示您尝试调用的本机C ++库是64位还是32位,因为您无法在64位进程中加载​​32位程序集。

Using a 32bit or 64bit dll in C# DllImport