Skip to content

Instantly share code, notes, and snippets.

@murphybytes
Created July 25, 2012 03:37
Show Gist options
  • Save murphybytes/3174220 to your computer and use it in GitHub Desktop.
Save murphybytes/3174220 to your computer and use it in GitHub Desktop.
Demonstrates using pinvoke to pass a callback from a .net managed application to a C dll
#ifndef _HEADER_H
#define _HEADER_H
typedef void (__stdcall *PFN_CALLBACK1)(const wchar_t* str);
extern "C" __declspec(dllexport) int __stdcall dllFunc(PFN_CALLBACK1 callback1 );
#endif
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace MyCSharpApp
{
class Program
{
public delegate void MyCallback1(IntPtr str);
// need to have the charset attribute set
[DllImport("../../../Debug/MyCDll.dll", CharSet = CharSet.Auto)]
public static extern void dllFunc(MyCallback1 callback1);
[DllImport("msvcrt.dll")]
public static extern int strlen(IntPtr ptr);
public static string Utf8PtrToString(IntPtr ptr)
{
if (ptr == IntPtr.Zero)
return null;
int len = strlen(ptr);
byte[] bytes = new byte[len];
Marshal.Copy(ptr, bytes, 0, len);
return System.Text.Encoding.UTF8.GetString(bytes);
}
public static void MyFunc1(IntPtr ucs2)
{
string text = Marshal.PtrToStringAuto(ucs2);
Console.WriteLine("I am Function 1... text {0}", text);
}
public static void MyFunc2(IntPtr utf8)
{
// this no worky
string text = Utf8PtrToString(utf8);
Console.WriteLine("I am Function 2; 한국; I got value {0}", text);
}
static void Main(string[] args)
{
MyCallback1 cb1 = new MyCallback1(MyFunc1);
dllFunc(cb1);
}
}
}
#include "stdio.h"
#include "header.h"
#include <string.h>
extern "C" __declspec(dllexport)
int __stdcall dllFunc(PFN_CALLBACK1 callback1) {
// the write to console won't handle the unicode
printf("you are inside the dll, こんにちは\n");
// these will work
callback1(L"hello 한국\n");
callback1(L"and hi hi 中国\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment