0

I want to pass image data to a C++ DLL function that looks like this:

GLFWcursor* glfwCreateCursor    (
    const GLFWimage* image,
    int xhot,
    int yhot 
)   

It crashes supposedly because of this struct (C#):

[StructLayout(LayoutKind.Sequential)]
public struct GlfwImage
{
    public int width;
    public int height;
    public byte[] pixels;
}

"pixels" is of type "unsigned char *", width and height are simple int-values.

While the method can be load with that signature, I always get a System.AccessViolationException when actually calling it.

I tried several datatypes for "pixels", including IntPtr and actual pointers but to no effect.

Here is how I get the data and call it:

var bufferSize = texture.Size.Width * texture.Size.Height * 4;

IntPtr imageData = Marshal.AllocHGlobal(bufferSize);

GL.GetTexImage(TextureTarget.Texture2D, 0, PixelFormat.Rgba, PixelType.Bitmap, imageData);

byte[] imageChars = new byte[bufferSize];

Marshal.Copy(imageData, imageChars, 0, bufferSize);

GlfwImage cursorImage = new GlfwImage
{
    pixels = imageChars,
    width = texture.Size.Width,
    height = texture.Size.Height
};

GlfwCursor cursor = Glfw.CreateCursor(cursorImage, texture.Size.Width / 2, texture.Size.Height / 2);

Is there something I'm overlooking?

S. Mense
  • 111
  • 1
  • 8
  • Show us the definition of `GlfwImage` in the C++! – Martin Bonner supports Monica Jan 24 '18 at 17:22
  • Also, does `GlfwImage` use one byte per pixel, or several? You are responsible for making sure that `pixels` points to `width*height` actual pixel data. – Martin Bonner supports Monica Jan 24 '18 at 17:23
  • http://www.glfw.org/docs/latest/structGLFWimage.html This is the documentation on it. I don't have the actual source code. – S. Mense Jan 24 '18 at 17:26
  • Is your program running as 32-bit? If so this is probably a calling convention mismatch. In 32-bit programs, C functions are by default exported as `__cdecl`, but P/Invoke defaults to `__stdcall` on x86 Windows. Use `[DllImport(/*...*/, CallingConvention=CallingConvention.Cdecl)]` if that's the case. See [this](https://stackoverflow.com/a/15664100/3446285) for more details. – Koby Duck Jan 25 '18 at 06:34
  • I'm already loading other methods with more simple parameters that work just fine. I tried it anyways but to no effect. I think the issue is the way the struct is defined. It is supposed to contain a pointer to a C char*, which can either be a string or just a pointer to a byte[] array right? – S. Mense Jan 25 '18 at 16:22

0 Answers0