首页 > 应用开发 > > 请指点一个在C#中调用C++动态链接库的问题
在C++中是这样写的
#define MAX_DEVICE_NAME_LENGTH 32
typedef char(*pDeviceArray)[MAX_DEVICE_NAME_LENGTH];
BV_ZFY_API int BV_ZFY_devices(int* count, pDeviceArray *devices_list)
{
GLOBAL_STATUS_CHECK();
if (!count || !devices_list || !devices_list[0])
return BVUSB_RESULT_E_INVALID_PARAM;
if (BVUSB_Result_SUCCEEDED(g_Global.BVUsbGetDevices(count, devices_list)))
return RESULT_FLAG_S_OK;
else return RESULT_FLAG_E_FAILED;
}
测试:
char szDeviceName[24] = { 0 };
pDeviceArray devArray;
int iDevCount = -1;
iResult = BV_ZFY_devices(&iDevCount, &devArray);
if (RESULT_FLAG_S_OK != iResult)
{
cout << "ERROR" << endl;
goto SYSTEM_PAUSE;
}以上为C++书写的代码,这个程序后来被编译成了libBVUsb.dll动态链接库,以上代码片断是没有办法再修改的。
现在我需要在我的程序中调用它,我目前这样写的:
[DllImport("libBVUsb.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall, EntryPoint = "BV_ZFY_devices")]
public static extern bool BV_ZFY_devices(ref int count, ref IntPtr devices_list);
传参:
int i = 0;
IntPtr pt = Marshal.AllocHGlobal(1);
var result = BV_ZFY_devices(ref i, ref pt);于是,就出错了!
错误内容为:
在调用时出错了,出错内容为:
对 PInvoke 函数“WindowsFormsApplication1!WindowsFormsApplication1.Form1::BV_ZFY_devices”的调用导致堆栈不对称。原因可能是托管的 PInvoke 签名与非托管的目标签名不匹配。请检查 PInvoke 签名的调用约定和参数与非托管的目标签名是否匹配。
应该是参数传错了,那正确的应该如何传呢?谢谢大家!
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/813/viewspace-3163795/ ,如需转载,请注明出处,否则将追究法律责任。