1、普通函数调用
2、dll内子线程回调函数
3、将dll内图片显示到c#句柄,需要使用d3d渲染技术
源码链接https://download.csdn.net/download/u011510016/77140864
c#端 ↓
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TestWinForms {
public partial class Form1 : Form {
//普通函数
[DllImport("TestDll.dll", EntryPoint = "Add", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]
public static extern int Add(int a, int b);
//回调函数
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void testEventCb(int eventId, String param1);
[DllImport("TestDll.dll", EntryPoint = "TestInit", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]
public static extern int TestInit(string param, string appid, testEventCb eventcb );
public static testEventCb mtestCoreEventCb;
public Form1() {
InitializeComponent();
mtestCoreEventCb = new testEventCb(OnTestEventCb);//委托-具体函数
TestInit("", "", mtestCoreEventCb);
}
private void BtnFunc_Click(object sender, EventArgs e) {
int a = Convert.ToInt16(textBox1.Text);
int b = Convert.ToInt16(textBox2.Text);
textBox3.Text = Add(a, b).ToString();
}
private void OnTestEventCb(int eventId, String param1) {
this.Invoke((Action)delegate () {
lblCallBack.Text = "eventId:" + eventId + " msg:" + param1;
});
}
}
}
c++端 ↓
// dllmain.cpp : 定义 DLL 应用程序的入口点。
#include "pch.h"
#include <iostream>
#include<thread>
#define EXPORT extern "C" __declspec (dllexport)
using namespace std;
EXPORT int Add(int a, int b);
typedef void (*TestEventCbFunc)(int eventID, const char* param1);
TestEventCbFunc mTestEvntCb;
EXPORT int TestInit(const char* param, const char* appid, TestEventCbFunc mCb);
void print1();
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
EXPORT int Add(int a, int b)
{
int add_result = a + b;
return add_result;
}
EXPORT int TestInit(const char* param, const char* appid, TestEventCbFunc mCb ) {
mTestEvntCb = mCb;
thread mythread1(print1);
mythread1.detach();
return 1;
}
void print1() {
while (true)
{
if (mTestEvntCb != NULL) {
mTestEvntCb(rand()%999, "testNum");
}
Sleep(1000);
}
}