在 C++/CLI 中从非托管调用托管代码时出错
我正在为程序编写“驱动程序”,该驱动程序与网络上的某些设备进行通信。我已经有了与这些设备配合使用的 C# 软件,因此计划重用代码。
因此,驱动程序 dll 实际上是程序和可用程序集之间的互操作,它是用 C++/CLI 编写的。程序调用接口中描述的方法,互操作dll调用C#代码,这就是我的看法。
我使用 #pragma unmanaged 实现了程序调用的方法
DeviceSearch::DeviceSearch(IDeviceSearchHandler* handler):m_handler(handler)
{
ManagedWrapper mw;
mw.Init();
}
ManagedWrapper 是在托管代码中实现的,显然
void ManagedWrapper::Init()
{
//some code
}
,但是这里出现了问题。如果 Init() 为空或调用 C++ 中定义的方法/类,则它可以正常工作。但是,如果我尝试调用 C# 代码(使用 #using 引用,其中 Facade.dll 是执行某些功能的 C# dll),则在调用 mw.Init() 时会出现访问冲突异常,甚至在调用 mw.Init() 时也不会出现访问冲突异常。它。
我是否遗漏了一些真正明显的我应该做的事情来使互操作正常工作?网络上的大多数信息只是告诉它应该“正常工作”
I'm writing a "driver" for a program, the driver communicates with some devices on network. I already have C# software working with the devices, so the plan is to reuse code.
So the driver dll is really an interop between program and and already availible assemblies, it's written in C++/CLI. The program calls methods described in interface, the interop dll calls C# code, that is how I see it.
I implement methods to be called by program using #pragma unmanaged
DeviceSearch::DeviceSearch(IDeviceSearchHandler* handler):m_handler(handler)
{
ManagedWrapper mw;
mw.Init();
}
ManagedWrapper is implemented in managed code, obviously
void ManagedWrapper::Init()
{
//some code
}
However, the problem rises here. If the Init() is empty or calls methods/classes defined in C++, it's working ok. However, if I try to call the C# code (which is referenced using #using , where Facade.dll is the C# dll which performs some functions), I get access violation exception right when mw.Init() is called, not even within it.
Am I missing something really obvious I should do to make the interop work? Most information in the net just tells that it should "just work"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看看这是否有帮助:
根据 How can i在 Win32 C++ 项目中使用 C# dll?
“在本机 C++ 代码中定义一个抽象接口类,然后在托管 C++ DLL 中创建一个具体子类。在方法实现中调用 C# 对象。
最后,导出一个工厂函数,它将实例化实现类并返回您的本机代码可以使用的基类指针。”
See if this helps:
According to How can i use a C# dll in a Win32 C++ project?
"Define an abstract interface class in your native C++ code, then create a concrete subclass inside the managed C++ DLL. Call into your C# objects in the method implementations.
Finally, export a factory function that will instantiate the implementation class and return a base-class pointer that your native code can use."