前言
llImport导入C++的动态链接库
1、使用步骤
1.用C#创建控制台应用程序,将生成的C++DLL拷贝到工程根目录下。
2.简单介绍DllImport的几个关键属性:
EntryPoint:我们要从DLL中导入的函数名称;(Sum)
CharSet:指示用在入口点种的字符集;(Ansi)
CallingConvention:指示入口点的调用约定;(StdCall)
3.使用DllImport,首先要引用 System.Runtime.InteropServices 命名空间;主要代码如下:
项目代码
github仓库:https://github.com/2012Netsky/CSharp_CPlusPlus_Dll
2、 C++程序
代码如下(示例):
export.h
/*
* 定义宏开关,标识是向DLL导出函数还是从DLL导入函数
*/
#ifndef EXPORT_H_
#define EXPORT_H_
#define DLL_EXPORTS
#endif
C++DLL.h
/*****************************************************
* 封装DLL头文件
*****************************************************/
#ifndef C_DLL_H_
#define C_DLL_H_
#ifdef __cplusplus
extern "C"{
#endif
#define DLL_STD_CALL __stdcall /* 1、函数参数由右向左入栈 2、函数调用结束后由被调用函数清除栈内数据 3、函数名字 */
#ifdef DLL_EXPORTS
#define DLL_STD_CAPI __declspec(dllexport)
#else
#define DLL_STD_CAPI __declspec(dllimport) /* 别的工程引用头文件,DLL_STD_CAPI代表从DLL导入函数 */
#endif
DLL_STD_CAPI int DLL_STD_CALL Sum(int ,int);
#ifdef __cplusplus
}
#endif
#endif
C++DLL.cpp
// C++DLL.cpp : 定义 DLL 应用程序的导出函数。
#include "export.h"
#include "C++DLL.h"
/* 定义导出函数 */
DLL_STD_CAPI int DLL_STD_CALL Sum(int a ,int b)
{
return a + b;
}
3、 C#程序
代码如下(示例):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
//可以正常使用
namespace ConsoleTestDll
{
class Program
{
/* 导入C++DLL */
[DllImport("C++DLL.dll", EntryPoint = "Sum", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int Sum(int a, int b); /* 声明为外部函数 */
static void Main(string[] args)
{
int ret = Program.Sum(3,4);
Console.WriteLine(ret);
Console.ReadLine();
}
}
}
总结
提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了pandas的使用,而pandas提供了大量能使我们快速便捷地处理数据的函数和方法。