开发者

Using native c++ code in c# - problem with std::vector

I want to use my native c++ functions from dll in managed c# code. But my functions take arguments like std::开发者_运维问答vector& - a vector reference... How I can implement this argument in dllimport statement? I know for example that there are IntPtr and so on but what will be for std::vector<>?


I would export "C" functions that wrap the needed functionality and P/Invoke them from C#. Such a "C" function could expose the std::vector<> data as a pointer and the size of the data buffer.

Say for instance that you have a std::vector<byte_t> in a class Buffer:

class Buffer
{
public:
    const std::vector<byte_t>& GetData() const { return data_; }

private:
    std::vector<byte_t> data_;
};

Then you can export a "C" function to properly scope the Bufferyou want to use:

Buffer* CreateBuffer();

And you probably want to do something on the native side that fills the std::vector<byte_t> with data:

void DoSomethingThatProduceData(Buffer* buffer);

Then you can read that data:

void GetBufferData(const Buffer* buffer, const byte_t** data, int* size);

And last, clean up:

void DestroyBuffer(Buffer* buffer);

Translate those "C" declarations to P/Invoke ones on the C# side:

[DllImport("YourBufferLib.dll")]
static extern IntPtr CreateBuffer();

[DllImport("YourBufferLib.dll")]
static extern void DoSomethingThatProduceData(IntPtr buffer);

[DllImport("YourBufferLib.dll")]
static extern void GetBufferData(IntPtr buffer, out IntPtr data, out Int32 size);

[DllImport("YourBufferLib.dll")]
static extern void DestroyBuffer(IntPtr buffer);

It would be A Good Thing to wrap those calls on the managed side in a IDisposable class that ensures that the native resource is properly cleaned up.

[The, somewhat trivial, implementation details of the "C" functions are obviously left as an exercise for the reader.]


STL vectors are unmanaged templated methods. In theory you can calculate the offsets to the corresponding methods of vector do some code generation and call it. You cannot use DllImport because the STL vectors are a template only library which are not exported methods. You could of course write a C style wrapper to call specific methods like

int GetSize(vector<xxx> *vec)
{
    return vec.size();
}

But you do not want to do that because the many managed unmanged transitions needed for this will bring your application to a sudden halt. If you need to manipulate stl vectors your best bet is to use managed C++ and call from C# into your Managed C++ dll to manipulate the vectors as you like. In many companies the usage of Managed C++ was banned becaus people did not pay attention to the cost of managed unmanaged transitions which did cause C++ to loose its main asset: Speed.

Yours, Alois Kraus

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜