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 Buffer
you 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.]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With