Last active
December 20, 2015 02:49
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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