c++代码:
#include "stdafx.h"
#include <windows.h>
extern "C" _declspec(dllexport) void fun(); //输出函数声明
#ifdef _MANAGED
#pragma managed(push, off)
#endif
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
void _declspec(dllexport) fun() //输出函数定义
{
MessageBoxW(NULL,TEXT("hello!!!"), TEXT("demo"), MB_OK);
}
#ifdef _MANAGED
#pragma managed(pop)
#endif
这个dll是这样定义的:
声明一个dllexport 函数 格式 extern ''C" _declspec(dllexport) void fun();
定义这样dllexport函数 格式 void _declspec(dllexport) fun();
C#代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace invoke_dll_fun
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int[] a1 = new int[] { 1, 2, 3 };
static int i=0; //写在函数button1_Click外边,class里面
[DllImport("dll.dll")]
public static extern void fun();
private void click_Click(object sender, EventArgs e)
{
textBox1.Text = a1[i%3].ToString();
i++;
fun();
}
}
}
注意:
[DllImport("dll.dll")]
public static extern void fun();
这两行是关键,导入dll文件,然后声明这个外部函数,最后在click方法里面调用fun()方法,以达到c++ c# 混合编程的效果。
遇到问题
1.错误CS0246: 找不到类型或命名空间名称“DllImport”(是否缺少using 指令或程序集引用?)
加上
using System.Runtime.InteropServices;解决问题
2.如果在dll创建的时候不加上关键字_declspec(dllexport) 这样写出来的函数是不能出现在输出表中的3.创建dll的时候默认字符集是unicode,这样在传字符串的时候会出现错误,需要修改字符集,设置为空