创建非托管C ++在C#中的对象对象

2023-09-02 20:49:27 作者:小恶魔

我有一个非托管的DLL在它的类MyClass的。 现在有一种方法来创建这个类在C#code的一个实例?要调用它的构造函数?我试过,但在Visual Studio报告一个消息,该存储区已损坏或错误的东西。

在此先感谢

解决方案

C#中不能创建类的实例从本地DLL导出。你有两个选择:

创建C ++ / CLI包装。这是.NET类库可以添加作为参考任何其他.NET项目。在内部,C ++ / CLI类的工作与非托管类,链接到由标准的C ++规则,本机DLL。对于.NET客户端,这个C ++ / CLI类看起来像.NET类。

编写C包装C ++类,可用于.NET客户端的PInvoke。例如,过分简化的C ++类:

MyClass类()
{
上市:
    MyClass的(INT N){M_DATA = N;}
    〜MyClass的(){}
    INT的GetData(){返回N;}
私人:
    int数据;
};

C API包装这个类:

无效*的CreateInstance()
{
    MyClass的* p =新MyClass的();
    返回磷;
}

无效ReleaseInstance(无效* pInstance)
{
    MyClass的* P =(MyClass的*)pInstance;
    删除磷;
}

INT的GetData(无效* pInstance)
{
    MyClass的* P =(MyClass的*)pInstance;
    返回对 - >的GetData();
}

//写包裹函数为每个MyClass的公共方法。
//每一个包装函数的第一个参数是类的实例。

的CreateInstance,ReleaseInstance和的GetData可以在C#中的客户端使用PInvoke的声明,并直接调用。 void *的参数应在PInvoke的声明中被声明为IntPtr的。

基于C 实现非托管 DLL 的计算器程序设计

I have an unmanaged dll with a class "MyClass" in it. Now is there a way to create an instance of this class in C# code? To call its constructor? I tried but the visual studio reports an error with a message that this memory area is corrupted or something.

Thanks in advance

解决方案

C# cannot create class instance exported from native Dll. You have two options:

Create C++/CLI wrapper. This is .NET Class Library which can be added as Reference to any other .NET project. Internally, C++/CLI class works with unmanaged class, linking to native Dll by standard C++ rules. For .NET client, this C++/CLI class looks like .NET class.

Write C wrapper for C++ class, which can be used by .NET client with PInvoke. For example, over-simplified C++ class:

class MyClass()
{
public:
    MyClass(int n){m_data=n;}
    ~MyClass(){}
    int GetData(){return n;}
private:
    int data;
};

C API wrapper for this class:

void* CreateInstance()
{
    MyClass* p = new MyClass();
    return p;
}

void ReleaseInstance(void* pInstance)
{
    MyClass* p = (MyClass*)pInstance;
    delete p;
}

int GetData(void* pInstance)
{
    MyClass* p = (MyClass*)pInstance;
    return p->GetData();
}

// Write wrapper function for every MyClass public method.
// First parameter of every wrapper function should be class instance.

CreateInstance, ReleaseInstance and GetData may be declared in C# client using PInvoke, and called directly. void* parameter should be declared as IntPtr in PInvoke declaration.