Let's say I have a C# program which needs some implementation done in C++(machine learning for example). For this I want a DLL which opens a video stream, processes "things" and then my C# program can grab those "things".
I find countless examples on how to create a DLL and calling functions of the DLL like "ShowImage()
" or "GetImage(image_struct *theImage)
"...where the latter you allocate memory in C# and let the C++ DLL read into it.
Here a DLL fills the data object with something...data object is created inside C# code
C++ code
extern "C" void __declspec(dllexport) __stdcall GetRawImageBytes(unsigned char* data, int width, int height)
{
unsigned char* final = someAwesomeDataGenerated();
std::memcpy(data, final.data, final.total() * final.elemSize());
}
C# Code
//Declarations
[DllImport("OpenCVDLL")]
private static extern void GetRawImageBytes(IntPtr data, int width, int height);
private GCHandle pixelHandle;
private IntPtr pixelPtr;
private Color32[] pixel32;
//later in some function...
pixel32 = tex.GetPixels32();
pixelHandle = GCHandle.Alloc(pixel32, GCHandleType.Pinned);
pixelPtr = pixelHandle.AddrOfPinnedObject();
GetRawImageBytes(pixelPtr, tex.width, tex.height);
This is an example of how I handle receiving images currently.
Now I explain which use case I find no real example/explanation of how to do:
I want objects to be created and hold by the DLL, meaning that the lifetime of objects is longer than only the single function call I make.
In a pure C++ environment I would do something like the following:
pseudo code
main()
{
Dll.createSomeObject();
Dll.InitializeObject();
float valueFromDLL = Dll.GiveMeSomething();
Dll.DeleteObject();
}
But how do I model this with C# ? Note that my main concern is about the lifetime of "SomeObject" in the Dll example here.