i have a function which is called from a library in C++ that has been imported to a C# project
I think it is asking for a pointer to an array. But I'm not sure how to make it work.
here is what it is asking for function(float*, float*);
but if i do something like
float[] f = {};
float[] f1 = {};
function(f,f1);
it says there are invalid arguments.
float * is a float pointer type in C#.
If the function is expecting float pointer arguments (float *), then the function must be presumed to work on pointers, possibly involving pointer arithmetic. It is therefore important to preserve that signature.
To pass float arrays in C# as float pointers (float*), you need to pin/fix the arrays in memory in an unsafe context to acquire a pointer to them that you can pass to the function to preserve its functionality:
unsafe
{
fixed (float* ptr_f = f) //or equivalently "... = &f[0]" address of f[0]
fixed (float* ptr_f2 = f2) //or equivalently "... = &f2[0]" address of f2[0]
{
function( ptr_f, ptr_f2 );
}
}
You will also need to mark your assembly as unsafe (in project properties > build tab > allow unsafe code checkbox).
If this is a method imported via DLLImport()
you can simply replace the array pointers with the typed array.
So a signature:
[DLLImport("some.dll")]
SomeMethod(int* a, float* b)
Becomes
[DLLImport("some.dll")]
SomeMethod(int[] a, float[] b)
Please note that this assumes the original c/c++ method was expecting an array. This won't work if the pointers are not intended to reference arrays.
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