3

Im trying to Marshall a C struct into C# like so

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct Shader
{
    public uint id;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = Raylib.MAX_SHADER_LOCATIONS)]
    public int[] locs;
}

And its C counterpart:

typedef struct Shader {
    unsigned int id;                // Shader program id
    int locs[MAX_SHADER_LOCATIONS]; // Shader locations array
} Shader;

MAX_SHADER_LOCATIONS is a constant set to 32 in both C and C#.

This solution here is the same as this Marshaling C++ struct with fixed size array into C#.

The function I am using to test it is

[DllImport(nativeLibName,CallingConvention = CallingConvention.Cdecl)]
public static extern Shader LoadShader(string vsFileName, string fsFileName);

And its C counterpart:

Shader LoadShader(const char *vsFileName, const char *fsFileName)

When I try to use this function I get the error "Method's type signature is not PInvoke compatible". Any idea what I'm doing wrong?

3
  • 1
    I checked and it returns a Shader struct not a pointer. I added the C version to the question. Commented Oct 12, 2018 at 12:38
  • 2
    The return type is the problem. It is not a "blittable" struct because of the array, that requires the pinvoke marshaller to create the managed struct, copy the data and destroy the C struct. The latter is the problem, it doesn't know how to do that. If you can change the C function then give it an extra argument, Shader*. Pretty important that you do, this function always needs some way to indicate failure. Give it an int return value for an error code. Only other thing you can do is use a fixed-size buffer instead of the array, public fixed locs int[32]; Commented Oct 12, 2018 at 12:49
  • 1
    I used fixed before but it requires that I compile as unsafe. So there isn't a way to Marshall a fixed array like that then? I can't really change the signature of the C function as it is part of a library. Commented Oct 12, 2018 at 13:10

0

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.