我正在尝试在C++/CLI中围绕.Net库创建一个本机包装器,以便常规C++代码可以使用它.对于这个例子,假设这是我试图包装的C#代码:
class Foo
{
public Bar GetBar() {...}
public string SomeProperty { get; set; }
}
class Bar
{
public void Baz() {...}
}
Run Code Online (Sandbox Code Playgroud)
我基本上是在C++/CLI(dll项目)中大致尝试这样做:
class __declspec(dllexport) NativeFoo
{
public:
NativeBar GetBar();
std::string GetName();
void SetName(const std::string &value);
private:
Foo ^m_foo;
};
class __declspec(dllexport) NativeBar
{
friend class NativeFoo;
public:
void Baz();
private:
Bar(Bar ^bar);
Bar ^m_bar;
};
Run Code Online (Sandbox Code Playgroud)
这样,C++库可以链接到这个,使用NativeFoo就好像它是一个普通的C++类.在内部,NativeFoo将转换参数以将实现传递给m_foo,将任何管理的内容编组回本机表示并将其返回给其调用者...
但是,我遇到的问题是我不能拥有非托管类的托管成员:
error C3265: cannot declare a managed 'm_bar' in an unmanaged 'NativeFoo'
Run Code Online (Sandbox Code Playgroud)
类似地,我不能将NativeFoo标记为"ref"(作为托管类本身)因为那时我无法导出它:
C3386: 'NativeFoo' : __declspec(dllexport)/__declspec(dllimport) cannot be applied to a managed type
Run Code Online (Sandbox Code Playgroud)
在我的C++对象中使用托管指针的正确方法是什么?
您需要使用gcroot在非托管类型上声明托管句柄.对于任何非托管类型,无论是否为dllexport,都需要这个.
它上面有一个MSDN页面,里面有一些很好的信息和一些样本.
我相信你最终会得到这样的东西:
class __declspec(dllexport) NativeFoo
{
public:
NativeBar GetBar();
std::string GetName();
void SetName(const std::string &value);
private:
gcroot<Foo^> m_foo;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3507 次 |
| 最近记录: |