在C#中使用C ++ DLL中的导出类 [英] Using an exported class from a C++ DLL in C#

查看:89
本文介绍了在C#中使用C ++ DLL中的导出类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我想在c#winform应用程序中使用c ++ dll



Dll导出一个继承自另一个基类的类(CMyClass)。



导出由包装器完成,该包装器以这种方式封装CTor DTor和另一个函数:



externC{

extern __declspec(dllexport)CMyClass * CreateMyClass();

.DTor ..

。功能..

}



和CreateMyClass是这样的:





CMyClass * CreateMyClass(){return new CMyClass();}





在c#中调用CreateMyClass是通过声明

[DllImport(MyDllPath .....)]

static public extern IntPtr CreateMyClass();



然后调用IntPtr p = CreateMyClass()。



调用失败试图读取或写入受保护的内存



是否有可能le调用一个c ++类,它是c#中的派生类?



谢谢!!



< b>我尝试了什么:



这个dll在另一个C ++应用程序中工作正常。



C#app。如果CMyClass不是派生类,则成功调用CreateMyClass

解决方案

简而言之:在类中编写COM包装器。



您可以使用编组或 C ++ COM Interop 执行此操作,如下所述微软。这是一篇如何制作C ++类的文章,其中包含一个演示项目

Hi all,

I am trying to use a c++ dll in c# winform application

The Dll exports a class (CMyClass) which inherits from another base class.

The export is done by a wrapper which encapsulates the CTor DTor and another function in this manner:

extern "C" {
extern __declspec(dllexport) CMyClass* CreateMyClass();
.DTor..
.function..
}

and CreateMyClass is something like that:


CMyClass* CreateMyClass (){return new CMyClass();}


The call to CreateMyClass in c# is done by declaring
[DllImport("MyDllPath.....")]
static public extern IntPtr CreateMyClass ();

and then calling IntPtr p = CreateMyClass() .

The call fails with Attempted to read or write protected memory"

Is it possible to invoke a c++ class which is a derived class in c#?

Thanks!!

What I have tried:

The dll works fine in an another C++ app.

The C# app. succeeded in calling the CreateMyClass if CMyClass is not a derived class

解决方案

In a nutshell: write a COM wrapper around the class.

You can do this with Marshalling or C++ COM Interop as described by Microsoft. Here is an article How to Marshal a C++ Class which has a demo project included.


这篇关于在C#中使用C ++ DLL中的导出类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆