1

I have a function like this :

extern "C" __declspec(dllexport) void Step(int * oSamplesCount, float * oSamples){
    // (approximative syntax for clarity)
    *oSamplesCount = new_samples_count (some number between 0 and 16000)
    oSamples[ 0 .. new_samples_count ] = some floats (sound data)
}

I'd like to call it from C# :

float [] mSamples = new float[16000];

[DllImport("Lib.dll")]
static extern void Step(ref Int32 oSamplesCount, [MarshalAs(UnmanagedType.LPArray,SizeConst=16000)] ref float [] oSamples);

void update(){
    Int32 lSamplesCount = 0;
    Step(ref lSamplesCount, ref mSamples);
}

The C function is called correctly, the for() loop that fills the samples array is ok, but it crashes somewhere between the return and the next C# line, so I guess it has something to do with unmarshalling, although I don't want any marshalling/unmarshalling (the array is blittable and must be written to from C)

I can't use /unsafe. I tried SizeConst and various other permutations.

Any help is appreciated !

1 Answer 1

1

Your pinvoke is wrong. The array parameter should not be passed by ref since a float[] is already a reference. Do it like this:

[DllImport("Lib.dll")]
static extern void Step(ref Int32 oSamplesCount, float[] oSamples);

Note that this will marshal from managed to native, and back again, all 16000 values, on each call to Step. If that's too expensive then I think you will need to perform manual marshalling.

Sign up to request clarification or add additional context in comments.

2 Comments

You're right, float[] is already a reference. That was my mistake. But if I use UnmanagedType.LPArray, will it still marshall/unmarshall the 16000 floats ?
Yes it will. The default marshalling for float[] is UnmanagedType.LPArray so you don't need to specify that. Your interface is very odd. The native code appends each time. I'd probably do this with AllocHGlobal and then copy all the floats into a float[] right at the end, once I'd finished calling Step.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.