Leon
Leon

Reputation: 135

Marshaling C++ int* to C#

I am trying to get a dll to work.

The DLL is written in C++, and it needs to pass int* to C#. I spent passed few days to get this to work, and it fails. I am starting to pull my hair out because I can not figure out what is wrong. I have tried everything. I am not as familiar with C++ as I am with C#, so problem might be coming from there...

It reads fine from the dll, but the values returned are not correct. I removed the inputs, and I am just trying to get a test array through. The function I am using in C++ is:

extern "C" EAGLE128DLL_API int* encryptFunc()
{
    //return encrypt(x, Q);

    int t[128];

    for(int i = 0; i < 128; i++)
    {
        t[i] = 5;
    }

    return t;
};

The C# code I use to call this function is as follows:

[DllImport("C:\\Users\\Leon\\Documents\\Visual Studio 2010\\Projects\\Eagle128DLL\\Release\\Eagle128DLL.dll")]
            public static extern IntPtr encryptFunc();
    ...

IntPtr outputPtr = encryptFunc();
int[] output = new int[128];

Marshal.Copy(outputPtr, output, 0, 128);

The values within output array should be all 5's. But what i get is: 16187392, 16190224..etc (not 5's)

Upvotes: 2

Views: 1927

Answers (2)

Pierre Arnaud
Pierre Arnaud

Reputation: 10547

The C++ code contains an error: you are returning a pointer to a variable stored on the stack (t[128] is only a temporary variable), which will not work. As soon as your encryptFunc returns, the call stack will be unwound and the variable t[128] will be trashed.

If your code needs not be re-entrant or thread safe, you can simply make t[128] static:

static int t[128];
...
return t;

A static variable will no longer be stored on the stack and will survive the end of the function.

Upvotes: 3

Tola Odejayi
Tola Odejayi

Reputation: 3059

I think that your problem is that you are trying to return a value that has been declared locally on the stack in your C function.

The best thing is to pass in a preallocated array to your C function which will receive the data that the function creates and return it back to the caller.

Upvotes: 2

Related Questions