Skip to content

Instantly share code, notes, and snippets.

@Porges
Last active December 20, 2015 02:49
Show Gist options
  • Save Porges/6059049 to your computer and use it in GitHub Desktop.
Save Porges/6059049 to your computer and use it in GitHub Desktop.
Receive an object passed from a C function to a callback. (Alternate definition using struct)
using System;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
struct Foo
{
public int Value;
}
class Program
{
// Declare type of callback function:
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void FooCallback(ref Foo passedObject);
// Declare native C function:
[DllImport("NativeDLL.dll")]
public static extern void InvokeCallbackWithObject(FooCallback callback);
static void Main(string[] args)
{
InvokeCallbackWithObject(MyCallback);
}
// The function receiving the object:
static void MyCallback(ref Foo passedObject)
{
Console.WriteLine("Got: " + passedObject.Value);
// mutate via pointer:
unsafe
{
fixed (Foo* fooPtr = &passedObject)
{
fooPtr->Value += 100;
}
}
Console.WriteLine("Got: " + passedObject.Value);
}
}
// Sorry, only have MSVC lying around...
#ifdef NATIVEDLL_EXPORTS
#define NATIVEDLL_API __declspec(dllexport)
#else
#define NATIVEDLL_API __declspec(dllimport)
#endif
extern "C"
{
struct Foo
{
int Value;
};
void NATIVEDLL_API InvokeCallbackWithObject(void (*func)(Foo*))
{
Foo myFoo;
myFoo.Value = 123;
func(&myFoo);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment