从C#/。NET调用C ++函数 [英] Call C++ functions from C#/.NET
问题描述
我有一个具有C ++项目和C#项目的解决方案。
C ++项目定义了一个类,该类要在C#中实例化并调用其成员。功能。到目前为止,我已经实例化了该类:
CFoo Bar = new CFoo();
但是当我尝试在其上调用函数时,编译器说它不可用。 / p>
此外,当我在调试器中检查对象时,未显示任何成员。
我在这里缺少什么?
您需要在C ++ / CLI中将类声明为 ref类
。
(请注意,我们谈论的是C ++ / CLI,而不是C ++。我假设您必须在C ++项目中启用了CLR,否则您不会就能使新的 CFoo
正常工作。)
编辑:
您不需要将所有旧类都转换为 ref
类。
假设您有一些旧的C ++:
class FooUnmanaged
{
int x;
FooUnmanaged():x(5){}
};
然后尝试将其包装到CLR类中:
ref class FooManaged
{
FooUnmanaged m;
};
您已经注意到,您收到一条错误消息,指出不允许这样做。但是,请尝试以下操作:
ref class FooManaged
{
FooUnmanaged * m;
};
那完全可以。编译器不想分配嵌入托管堆中对象内部的非托管对象的实例,但是很高兴有一个指针,它变成了 System.IntPtr
产生的IL。
这意味着您必须决定如何调用删除
。最可能的解决方案是:
ref class FooManaged
{
FooUnmanaged * u;
public:
FooManaged(FooUnmanaged * u_)
:u(u_){}
〜FooManaged(){删除u; }
};
就像在任何其他C ++类中一样。 C ++ / CLI可能会在将来的某些版本中自动为我们完成此翻译。
请注意,生成的IL是 FooManaged
类现在实现了 IDisposable
,并且析构函数已转换为 Dispose
方法。这允许.NET客户端正确地分配它,例如在C#
中使用(var m = new FooManaged())
{
/ /块末:m将被处置(因此FooUnmanaged将被删除)
}
I have a solution which has a C++ project and a C# project.
The C++ project defines a class, which I want to instantiate in C# and call its member functions. So far I managed to instantiate the class:
CFoo Bar = new CFoo();
But when I try to call a function on it, the compiler says, it is not available.
Also, when I inspect the object in the debugger, no members are shown.
What am I missing here?
You need to declare the class in C++/CLI as a ref class
.
(Note that we're talking about C++/CLI, not C++. I assume you must have enabled the CLR in your C++ project or you wouldn't be able to get the new CFoo
to work.)
Edit:
You don't need to convert all your old classes in to ref
classes.
Suppose you have some old C++:
class FooUnmanaged
{
int x;
FooUnmanaged() : x(5) {}
};
Then you try to wrap it in a CLR class:
ref class FooManaged
{
FooUnmanaged m;
};
As you've noticed, you get an error saying this isn't allowed. But try this:
ref class FooManaged
{
FooUnmanaged *m;
};
That's perfectly OK. The compiler doesn't want to allocate an instance of an unmanaged object embedded inside an object on the managed heap, but it's quite happy to have a pointer, which it turns into System.IntPtr
in the resulting IL.
This means that you have to make a decision about how to call delete
. The most likely solution is:
ref class FooManaged
{
FooUnmanaged *u;
public:
FooManaged(FooUnmanaged *u_)
: u(u_) { }
~FooManaged() { delete u; }
};
Just as it would be in any other C++ class. It's possible that C++/CLI will be able to do this translation for us automatically in some future version.
Note that the resulting IL is that the FooManaged
class now implements IDisposable
, and the destructor has been turned into a Dispose
method. This allows .NET clients to properly deallocate it, e.g. in C#
using (var m = new FooManaged())
{
// end of block: m will be disposed (and so FooUnmanaged will be deleted)
}
这篇关于从C#/。NET调用C ++函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!