我在非托管的Visual C++中编写了一个DLL,并且在使用C#和C++应用程序时遇到了一些问题。下面是原型在C++ DLL的样子:从托管代码调用非托管DLL函数时出错
extern "C" __declspec(dllexport) int WINAPI ZBNConnect(UCHAR dev, LPARAM hWnd, ZBCallbackFn rfn, ZBCallbackFn nfn, int DevType, byte * DevAddr, ZBCallbackFn dfn);
我的C#应用程序可以链接到的功能,没有问题,但是,当它试图调用一个抛出异常的函数:
catch (Exception e) { /* ... */ }
e.Message =“未将对象引用设置为对象的实例。”
奇怪的是,如果我将WINAPI
带出DLL中的原型,并重新编译,C#应用程序将调用该函数而不会有任何问题。不幸的是,WINAPI
必须保留,因为这是如何在C++应用程序中定义函数。
public delegate int ZBNConnectDelegate(uint dev, IntPtr hWnd, USBCallbackDelegate rfn, NotifyCallbackDelegate nfn, uint DevType, byte[] DevAddr, ZBdebugCallbackDelegate dfn);
public ZBNConnectDelegate ZBNConnect;
procName = "ZBNConnect";
fUintPtr = Kernel32.GetProcAddress(dllHandle, procName);
if (fUintPtr == UIntPtr.Zero)
{
throw new ArgumentException(procName);
}
fIntPtr = unchecked((IntPtr)(long)(ulong)fUintPtr);
ZBNConnect = (ZBNConnectDelegate)Marshal.GetDelegateForFunctionPointer(fIntPtr, typeof(ZBNConnectDelegate));
如何修改C#应用程序得到这个工作:
功能在C#应用程序一样,这是目前的原型?谢谢。
编辑:附加信息
静态链接([DllImport...]
)不是因为这取决于哪个硬件附接至系统,支持连接的硬件是在运行时加载的不同DLL的选项。这两个DLL都具有相同的API调用。
这不是DLL地狱,是完全不同的 – 2011-01-21 23:07:20
你试图把外部原型? – bratao 2011-01-21 23:17:32
那么,你如何初始化`ZBNConnect`并使其指向非托管函数呢?正如所写,它将是`null`。为什么不使用P/Invoke(`[DllImport] static extern`)? – 2011-01-22 00:00:39