首先,我想提及这个问题:Sharing variables between C# and C++。
这似乎是我要找的,但当我试图实现这一点时,我得到了一些错误。
首先这是我的代码:
C++
namespace CppWrapping
{
#pragma pack(1)
public struct MyPoint
{
public:
float X;
float Y;
float Z;
unsigned char R;
unsigned char G;
unsigned char B;
unsigned char A;
}MyPoint_t;
#pragma pack()
public ref class MyCppWrapper
{
public:
MyCpplWrapper(void);
List<MyPoint>^ getData();
};
};
C++MyCPPrPAPP.CPP
List<MyPoint>^ MyCppWrapper::getData()
{
List<MyPoint>^ temp = gcnew List<MyPoint>();
for (int i = 0; i < Data.Length; i++)
{
PointT& pt = Data.points[i];
MyPoint holder = MyPoint();
holder.X = pt.x;
holder.Y = pt.y;
holder.Z = pt.z;
holder.R = pt.r;
holder.G = pt.g;
holder.B = pt.b;
holder.A = pt.a;
temp[i] = holder;
}
return temp;
}
c mylinker.cs公司
[StructLayout(LayoutKind.Sequential, Pack = 1)]
private struct MyPoint_t
{
public float X;
public float Y;
public float Z;
public byte R;
public byte G;
public byte B;
public byte A;
};
public void getData()
{
_wrapper = new MyCppWrapper();
List<MyPoint_t> data = _wrapper.getData();
}
有很多错误,但归根结底是这三个错误:
error C3225: generic type argument for 'T' cannot be 'CppWrapping::MyPoint', it must be a value type or a handle to a reference type
'CppWrapping.MyPoint' is inaccessible due to its protection level
'CppWrapping.MyCppWrapper.getData()' is inaccessible due to its protection level
当我将光标悬停在代码
List data = _wrapper.getData();
下时,也会得到一个红色标记:Cannot convert source type 'System.Collections.Generic.List<CppWrapping.MyPoint>' to target type 'System.Collections.Generic.List<ProjectA.MyLinker.MyPoint_t>'
我该怎么解决?
编辑:
我把
public struct MyPoint
改成public value struct MyPoint
将错误数量从58减少到1。
我现在犯的错误是:
Cannot implicitly convert type 'System.Collections.Generic.List<CppWrapping.MyPoint>' to 'System.Collections.Generic.List<ProjectA.MyLinker.MyPoint_t>'
最佳答案
public struct MyPoint {}
这声明了一个非托管结构,您的c代码无法访问它,因为它被导出为没有任何成员的不透明值类型。你必须声明
public value struct MyPoint {}
接下来要做的是从C代码中删除MyPoint声明。类型标识包括该类型来自的程序集,因此mypoint\u t与mypoint不兼容。您可以简单地使用C++/CLI程序集中的MyPoT类型:
_wrapper = new MyCppWrapper();
List<MyPoint> data = _wrapper.getData();
或者利用c中的类型推断:
var data = _wrapper.getData();