Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What C# type stands for C++ float*?

Tags:

c#

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.

like image 449
user1395152 Avatar asked Mar 13 '13 20:03

user1395152


2 Answers

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).

like image 133
Triynko Avatar answered Oct 11 '22 09:10

Triynko


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.

like image 23
FlyingStreudel Avatar answered Oct 11 '22 09:10

FlyingStreudel