0

I'm trying to convert an object to an unsafe void*. Here's an example :

public static void glBufferData(uint target, ulong size, object data, uint usage)
{
    _glBufferData(target, size, data, usage);
}

Here are the parameters of _glBufferData :

uint target, ulong size, void* data, uint usage

I'm passing this object :

float[] positions =
{
    -0.5f, -0.5f,
    0.0f, 0.5f,
    0.5f, -0.5f
};

I tried this but it didn't work.

fixed (void* ptr = &data)
{
}

My class is unsafe by the way.
How can I do that ?

droyer
  • 71
  • 2
  • 7
  • I don't know if it's a dupe necessarily, but maybe [this question](https://stackoverflow.com/questions/15527985/what-is-void-in-c) will help? – Broots Waymb Apr 27 '21 at 17:20

2 Answers2

0

You cannot take the address of a variable of type object.

Change the type of the data parameter from object to float[] and use fixed to obtain the address of the first array element:

private static extern void _glBufferData(uint target, ulong size, void* data, uint usage);

public static void glBufferData(uint target, ulong size, float[] data, uint usage)
{
    fixed (float* ptr = &data[0])
    {
        _glBufferData(target, size, ptr, usage);
    }
}

You can also try changing void* to float[] in the signature of the _glBufferData method, which would eliminate the need to use fixed:

private static extern void _glBufferData(uint target, ulong size, float[] data, uint usage);

public static void glBufferData(uint target, ulong size, float[] data, uint usage)
{
    _glBufferData(target, size, ptr, usage);
}
Michael Liu
  • 52,147
  • 13
  • 117
  • 150
  • It's working, thank you. The downside is that I have to precise the type of the variable. Is there no other way do to that ? – droyer Apr 27 '21 at 19:20
  • With the first solution I posted, you can create additional overloads of `glBufferData` for each data type you need. All of them can call `_glBufferData`. – Michael Liu Apr 27 '21 at 19:26
  • This is what I'm gonna do. Thank you. – droyer Apr 27 '21 at 19:29
0
  1. Create a GCHandle for your object
IntPtr handle = (IntPtr) GCHandle.Alloc(this)
  1. Parse your handle as void*
glBufferData(target, size, (void*)handle, usage)
  1. Restore your object from the InPtr GCHandle
public static void glBufferData(uint target, ulong size, void* data, uint usage)
{
            GCHandle myObjectHandle = (GCHandle)((IntPtr)data);
            MyObject obj = (MyObject)myObjectHandle.Target;
}
SuRGeoNix
  • 482
  • 1
  • 3
  • 10