1

I try to import functions from my C-Dll. A function has a struct array as a parameter. The struct will be filled in the function.

struct test
{
    int test1;
    int test2;
};

void FillStruct( struct test stTest[], int size)
{
    if(size == 2){
        stTest[0].test1 = 5;
        stTest[0].test2 = 5;

        stTest[1].test1 = 2;
        stTest[1].test2 = 2;
    }
}

The method FillStruct should be used in C#.

I think I have to create the struct in C#. Must I marshal the struct if I use memcpy in the Fillstruct?

3
  • Just declare your own version of it, there's nothing complicated about a struct with two int members. The pinvoke marshaller takes care of marshaling the array and its elements. Nothing complicated either, it simply pins the array and passes a pointer to the first element. Writing C code that just doesn't do anything when the wrong argument is passed is a bad idea, return an error code. Commented May 30, 2015 at 20:31
  • Thanks a lot, i tried tu abstract the problem. In FillStruct i use memcpy. I hope this runs without any problems. Commented May 30, 2015 at 20:36
  • Well, never post fake code. Using memcpy() is fine, as long as you don't ignore size. Commented May 30, 2015 at 20:38

1 Answer 1

2
struct Test
{
    public int test1;
    public int test2;
}

[DllImport("mydll", CallingConvention = Cdecl)]
public static extern void FillStruct( Test[] stTest, int size);

[...]
var test = new Test[n];
FillStruct(test, test.Length);

I don't see the problem here. It does not matter what you do with the memory in your c code: as long as you don't cause buffer overflows, you can read, write an copy all you want. c# arrays are just the type and length of the array, followed by the data. When you use p/invoke with simple structs, a pointer to the first element in the original array will be passed to your c code.

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

Comments

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.