C ++互操作:如何调用从本地C ++ C#类,用捻类非静态? [英] C++ Interop: How do I call a C# class from native C++, with the twist the class is non-static?
问题描述
我有一个大的应用程序在编写本地C ++。我也有在C#中,我需要调用类
I have a large application written in native C++. I also have a class in C# that I need to call.
如果在C#类是静态的,那么这将是微不足道的(还有很多在网络上的例子)。 - 只写混合C ++ / CLI包装,输出接口,你就大功告成了。
If the C# class was static, then it would be trivial (there's lots of examples on the web) - just write the mixed C++/CLI wrapper, export the interfaces, and you're done.
不过,C#类是非静态的,不能更改,静态,因为它有一个接口(如果你试图让C#类的静态编译器将生成一个错误)
However, the C# class is non-static, and can't be changed to static as it has an interface (the compiler will generate an error if you attempt to make the C# class static).
有没有人碰到这个问题 - 怎么办我非静态的C#类导出到本地C ++?
Has anyone run into this problem before - how do I export a non-static C# class to native C++?
更新2010-11-09
最终的解决方案:尝试了COM,这个工作很好,但不支持结构。所以,去与一个C ++ / CLI的包装,因为我绝对需要的是能够通过C ++和C#之间的结构。我写的.dll包装根据代码在这里混合模式:
Final solution: tried COM, this worked nicely but didn't support structures. So, went with a C++/CLI wrapper, because I absolutely needed to be able to pass structures between C++ and C#. I wrote a mixed mode .dll wrapper based on the code here:
目标类是非静态的,我不得不使用Singleton模式以确保我只是实例化目标类的一个副本。这确保一切都足够快,以满足规范。
As the target class was non-static, I had to use the singleton pattern to make sure I was only instantiating one copy of the target class. This ensured everything was fast enough to meet the specs.
与我联系,如果你要我来发布演示项目(虽然是公平的,我打电话给C#从C ++,这几天大多数人想从C#调用C ++)。
Contact me if you want me to post a demo project (although, to be fair, I'm calling C# from C++, and these days most people want to call C++ from C#).
推荐答案
C ++ / CLI或的 COM互操作很好的工作与非静态类与静态的。使用C ++ / CLI中,您刚才提到的大会,持有非静态类,然后你可以使用 gcnew
来获取对新实例的引用。
C++/CLI or COM interop work just as well with non-static classes as with static. Using C++/CLI you just reference your assembly that holds the non-static class and then you can use gcnew
to obtain a reference to a new instance.
是什么让你认为这是不可能有你的非静态类
What makes you think that this is not possible with your non-static class?
编辑:有示例代码的这里。
using namespace System;
public ref class CSquare
{
private:
double sd;
public:
CSquare() : sd(0.00) {}
CSquare(double side) : sd(side) { }
~CSquare() { }
property double Side
{
double get() { return sd; }
void set(double s)
{
if( s <= 0 )
sd = 0.00;
else
sd = s;
}
}
property double Perimeter { double get() { return sd * 4; } }
property double Area { double get() { return sd * sd; } }
};
array<CSquare ^> ^ CreateSquares()
{
array<CSquare ^> ^ sqrs = gcnew array<CSquare ^>(5);
sqrs[0] = gcnew CSquare;
sqrs[0]->Side = 5.62;
sqrs[1] = gcnew CSquare;
sqrs[1]->Side = 770.448;
sqrs[2] = gcnew CSquare;
sqrs[2]->Side = 2442.08;
sqrs[3] = gcnew CSquare;
sqrs[3]->Side = 82.304;
sqrs[4] = gcnew CSquare;
sqrs[4]->Side = 640.1115;
return sqrs;
}
这篇关于C ++互操作:如何调用从本地C ++ C#类,用捻类非静态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!