您的位置:首页 > 编程语言 > C语言/C++

C#调用C++ dll,并向调用的函数传递“函数指针”

2015-01-27 19:23 363 查看
SocketBLL(C++dll项目):

BLL.h文件:

#pragma once
#include <Windows.h>
typedef void(*MsgManagement)(int);
MsgManagement MsgManage;
HANDLE h;
DWORD WINAPI RecieveTransientMsg(LPVOID pParam);
extern "C" _declspec(dllexport) void _stdcall Start(MsgManagement p);
extern "C" _declspec(dllexport) void _stdcall Wait();



BLL.cpp文件:

#include "BLL.h"

DWORD WINAPI RecieveTransientMsg(LPVOID pParam)
{
((MsgManagement)pParam)(2);
return 0;
}
extern "C" _declspec(dllexport) void _stdcall Start(MsgManagement p)
{
h = CreateThread(NULL, 0, RecieveTransientMsg, p, 0, NULL);
}
extern "C" _declspec(dllexport) void _stdcall Wait()
{
::WaitForSingleObject(h,INFINITE);
}


ConsoleServer(C#项目):

Program.cs文件:

命名空间:using System.Runtime.InteropServices;

class Program
{
public delegate void MsgManagement(int t);

[DllImport("SocketBLL.dll")]
public extern static void Start(MsgManagement callback);
[DllImport("SocketBLL.dll")]
public extern static void Wait();

static void myCout(int i)
{
Console.WriteLine(i);
}

static MsgManagement callback;
static void Main(string[] args)
{
callback = myCout;
Start(myCout);
Wait();
Console.WriteLine(1);
return;
}
}


参考:http://blog.chinaunix.net/uid-27226595-id-3463788.html  [简介:C#与C++交互,利用PInvoke实现直接调用,基本数据类型、指针、函数指针、结构体的传递]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: