Calling unmanaged c++ code in C# Mixed with STL

时光怂恿深爱的人放手 提交于 2019-12-07 19:39:36

问题


Hey, I want to call unmanaged c++ code in C# The function interface is like following(I simplified it to make it easy to understand)

Face genMesh(int param1, int param2);

Face is a struct defined as:

struct Face{
    vector<float> nodes;
    vector<int>  indexs;
}

I googled and read the MSDN docs found ways to call simple c/c++ unmanged code in C#, also know how to hand the struct as return value. And My question is how to handle "vector". I did not find rules about mapping between vector and some types in C#

Thanks!


回答1:


You want, if possible, to avoid using STL in anything but pure UNmanaged code. When you mix it with C++/CLI (or Managed C++), you will likely end up with the STL code running as managed and the client code running as unmanaged. What happens is that when you, say, iterate over a vector, every call to a vector method will transition into managed code and back again.

See here for a similar question.




回答2:


You're probably going to need to pass the raw arrays unless you really want to jump through some hoops with the interop as the rules specify the types have to either be marhallable by the framework, or you've given the framework a specific structure it can marshall. This probably is not possible for vector. So, you can define you C++ struct as

#pragma pack(push, 8)
struct ReflSettings
 {
double* Q;
    double* DisplayQ;
 }
 #pragma pack(pop)

then you C# struct would be

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 8)]
    public class ModelSettings:IDisposable
    {

        [XmlIgnore] internal IntPtr Q;
        [XmlIgnore] internal IntPtr DisplayQ;
    }

Hope this helps.




回答3:


Probably the simplest thing to do is to create a managed class in C++ to represent the 'Face' structand copy the it's contents into the new managed class. Your c# code should then be able to understand the data.

You could use an ArrayList in place of the vectors.



来源:https://stackoverflow.com/questions/2593602/calling-unmanaged-c-code-in-c-sharp-mixed-with-stl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!