背景

在项目过程中,有时候你需要调用非C#编写的DLL文件,尤其在使用一些第三方通讯组件的时候,通过C#来开发应用软件时,就需要利用DllImport特性进行方法调用。本篇文章将引导你快速理解这个调用的过程。

步骤

1. 创建一个CSharpInvokeCPP的解决方案:

2. 创建一个C++的动态库项目:

3. 在应用程序设置中,选择“DLL”,其他按照默认选项:

最后点击完成,得到如图所示项目:

我们可以看到这里有一些文件,其中dllmain.cpp作为定义DLL应用程序的入口点,它的作用跟exe文件有个main或者WinMain入口函数是一样的,它就是作为DLL的一个入口函数,实际上它是个可选的文件。它是在静态链接时或动态链接调用LoadLibrary和FreeLibrary时都会被调用。详细内容可以参考(http://blog.csdn.net/benkaoya/archive/2008/06/02/2504781.aspx)。

4. 现在我们打开CSharpInvokeCPP.CPPDemo.cpp文件:

现在我们加入以下内容:

// CSharpInvokeCpp_CppDemo.cpp : 定义 DLL 应用程序的导出函数。
// #include "stdafx.h" extern "C" __declspec(dllexport) int Add(int x, int y)
{
return x + y;
}
extern "C" __declspec(dllexport) int Sub(int x, int y)
{
return x - y;
} extern "C" __declspec(dllexport) int Multiply(int x, int y)
{
return x * y;
}
extern "C" __declspec(dllexport) int Divide(int x, int y)
{
return x / y;
}

  

extern "C" 包含双重含义,从字面上即可得到:首先,被它修饰的目标是“extern”的;其次,被它修饰的目标是“C”的。而被extern "C"修饰的变量和函数是按照C语言方式编译和连接的。

__declspec(dllexport)的目的是为了将对应的函数放入到DLL动态库中。

extern "C" __declspec(dllexport)加起来的目的是为了使用DllImport调用非托管C++的DLL文件。因为使用DllImport只能调用由C语言函数做成的DLL。

5. 编译项目程序,最后在Debug目录生成CSharpInvokeCPP.CPPDemo.dll和CSharpInvokeCPP.CPPDemo.lib

可以发现对外的公共函数上包含这四种“加减乘除”方法。

6. 现在来演示下如何利用C#项目来调用非托管C++的DLL,首先创建C#控制台应用程序:

7. 在CSharpInvokeCSharp.CSharpDemo项目上新建一个CPPDLL类,编写以下代码:

public class CppDLL
{
[DllImport("CSharpInvokeCpp_CppDemo.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int Add(int x, int y); [DllImport("CSharpInvokeCpp_CppDemo.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int Sub(int x, int y); [DllImport("CSharpInvokeCpp_CppDemo.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int Multiply(int x, int y); [DllImport("CSharpInvokeCpp_CppDemo.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int Divide(int x, int y); }

  DllImport作为C#中对C++的DLL类的导入入口特征,并通过static extern对extern “C”进行对应。其中CallingConvention是声明函数的调用方式,也就是确定函数参数的入栈顺序。

8. 另外,记得把CPPDemo中生成的DLL文件拷贝到CSharpDemo的bin\Debug或者bin\Release目录下。另外,如果嫌一直拷贝麻烦,你也可以通过设置DLL工程的项目属性,【项目属性】->【配置属性】->【常规】中的输出目录:

这样,每次重新编译的DLL文件就自动的输出到了使用它的C#工程的目录下。

9. 然后在C#的测试类的Main入口编写测试代码:

static void Main(string[] args)
{
    int result = CPPDLL.Add(10, 20);
    Console.WriteLine("10 + 20 = {0}", result);
 
    result = CPPDLL.Sub(30, 12);
    Console.WriteLine("30 - 12 = {0}", result);
 
    result = CPPDLL.Multiply(5, 4);
    Console.WriteLine("5 * 4 = {0}", result);
 
    result = CPPDLL.Divide(30, 5);
    Console.WriteLine("30 / 5 = {0}", result);
 
    Console.ReadLine();
}

 测试代码运行结果:

10. 以上的方法只能通过静态方法对于C++中的函数进行调用。那么怎样通过静态方法去调用C++中一个类对象中的方法呢?现在我在CPPDemo项目中添加一个头文件userinfo.h:

class UserInfo {
private:
    char* m_Name;
    int m_Age;
public:
    UserInfo(char* name, int age)
    {
        m_Name = name;
        m_Age = age;
    }
    virtual ~UserInfo(){ }
    int GetAge() { return m_Age; }
    char* GetName() { return m_Name; }
};

  在CSharpInvokeCPP.CPPDemo.cpp中,添加一些代码:

#include <malloc.h>
#include "userinfo.h" typedef struct
{
char name[32];
int age;
}User;
UserInfo *userInfo; extern "C" __declspec(dllexport) User* Create(char *name, int age)
{
User *user = (User *)malloc(sizeof(User)); userInfo = new UserInfo(name, age);
strcpy(user->name, userInfo->GetName());
user->age = userInfo->GetAge(); return user;
}

  

这里声明一个结构,包括name和age,这个结构是用于和C#方面的结构作个映射。

注意:代码中的User*是个指针,返回也是一个对象指针,这样做为了防止方法作用域结束后的局部变量的释放。

strcpy是个复制char数组的函数。

11. 在CSharpDemo项目中CPPDLL类中补充代码:

[DllImport("CSharpInvokeCPP.CPPDemo.dll")]
public static extern IntPtr Create(string name, int age); [StructLayout(LayoutKind.Sequential)]
public struct User
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string Name; public int Age;
}

  其中这里的结构User就和C++中的User对应。

12. 在Program.cs中补充代码:

IntPtr ptr = CppDLL.Create("stemon", 26);
CppDLL.User user = (CppDLL.User)System.Runtime.InteropServices.Marshal.PtrToStructure(ptr, typeof(CppDLL.User));
Console.WriteLine("Name: {0}, age: {1}", user.name, user.age);

这里结构指针首先转换成IntPtr句柄,然后通过Marshal.PtrToStructrue转换成你所需要的结构。

注意:

非托管的代码中如果有类,使用的方法就是上面的这个样子,把类转换成C语言的结构体,因为DLL只能是C语言的。如果非托管的类是一个功能类,那么就不用结构体了,直接使用C语言的一些函数调用非托管类的成员函数,也就是说把C语言的函数当做DLL对外的接口,有C语言的这些接口函数去调用非托管代码的功能函数。但是要在调用其他函数之前利用一个Init()函数,实例化出来一个类的对象。(当然了,如果所有的成员函数都是静态的,那就不用实例对象了,直接使用类调用函数就可以了。)

PtrToStructure这个函数

Marshal.PtrToStructure 方法 (IntPtr, Type)
ptr
类型:System.IntPtr 指向非托管内存块的指针。 structureType
类型:System.Type 待创建对象的类型。 此对象必须表示格式化类或结构。
返回值
类型:System.Object 一个托管对象,包含 ptr 参数指向的数据。

  将数据从非托管内存块封送到新分配的指定类型的托管对象。

using System;
using System.Runtime.InteropServices; public struct Point
{
public int x;
public int y;
} class Example
{ static void Main()
{ // Create a point struct.
Point p;
p.x = 1;
p.y = 1; Console.WriteLine("The value of first point is " + p.x + " and " + p.y + "."); // Initialize unmanged memory to hold the struct.
IntPtr pnt = Marshal.AllocHGlobal(Marshal.SizeOf(p)); try
{ // Copy the struct to unmanaged memory.
Marshal.StructureToPtr(p, pnt, false); // Create another point.
Point anotherP; // Set this Point to the value of the
// Point in unmanaged memory.
        //函数的返回值是一个object类型,所以要强制的再转换一下
anotherP = (Point)Marshal.PtrToStructure(pnt, typeof(Point)); Console.WriteLine("The value of new point is " + anotherP.x + " and " + anotherP.y + "."); }
finally
{
// Free the unmanaged memory.
Marshal.FreeHGlobal(pnt);
} }
}

  

在VS2010上使用C#调用非托管C++生成的DLL文件的更多相关文章

  1. 【转】在VS2010上使用C#调用非托管C++生成的DLL文件(图文讲解)

    原文:http://www.cyqdata.com/cnblogs/article-detail-35876# 背景 在项目过程中,有时候你需要调用非C#编写的DLL文件,尤其在使用一些第三方通讯组件 ...

  2. 在VS2010上使用C#调用非托管C++生成的DLL文件(图文讲解)

    http://www.cyqdata.com/cnblogs/article-detail-35876#

  3. 在VS2017上使用C#调用非托管C++生成的DLL文件(图文讲解)

    原文:在VS2010上使用C#调用非托管C++生成的DLL文件(图文讲解) 背景 在项目过程中,有时候你需要调用非C#编写的DLL文件,尤其在使用一些第三方通讯组件的时候,通过C#来开发应用软件时,就 ...

  4. (转)C#调用非托管Win 32 DLL

    转载学习收藏,原文地址http://www.cnblogs.com/mywebname/articles/2291876.html 背景 在项目过程中,有时候你需要调用非C#编写的DLL文件,尤其在使 ...

  5. 关于C#调用非托管DLL,报“内存已损坏的”坑,坑,坑

    因客户需求,与第三方对接,调用非托管DLL,之前正常对接的程序,却总是报“内存已损坏的异常”,程序进程直接死掉,折腾到这个点(2018-05-11 00:26),终于尘埃落定,直接上程序. 之前的程序 ...

  6. 关于C#调用非托管动态库方式的性能疑问

    最近的项目中,因为一些原因,需要C#调用非托管(这里为C++)的动态库.网上喜闻乐见的方式是采用静态(DllImport)方式进行调用.偶然在园子里看到可以用动态(LoadLibrary,GetPro ...

  7. asp.net调用非托管dll,无法加载 DLL,找不到指定模块解决方法。

    最近开发一个项目,里面用到了非.net开发的一个dll文件接口,发现发布到window2003服务器上后,运行网站总是提示 "无法加载 DLL"D:\11\1.dll": ...

  8. 非系统盘根目录出现msdia80.dll文件,能否删除?

    出现此问题的原因:计算机上安装了 Microsoft Visual C++ 2005 可再发行组件时,Msdia80.dll文件被错误安装在其他驱动器的根文件夹中. 它的正确路径应该是"C: ...

  9. C++调用C#生成的DLL文件的各种问题

    C++调用C#生成的DLL文件: 首先选择建立一个C#的类库,然后再按照需求编写需要的函数 之后,对于C++调用过程需要注意的几点: 1.使用#using <....some.dll>指出 ...

随机推荐

  1. MySQL 用户登录与操作执行

    一个用户可以不登录进Mysql 数据库,由两方面的因数决定 1.你是谁:也就是mysql 数据库中记录的用户名和密码,在SQL Server数据库,中只要求说明你是谁就可以登录了,可是mysql 不是 ...

  2. Qt项目管理(33个规则)

    2016-06-20 花莫弦 小小杂货铺LY 一.qmake的介绍 qmake是Trolltech公司创建的用来为不同的平台和编译器书写Makefile的工具. 手写Makefile是比较困难并且容易 ...

  3. 数据库 BUG:Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '=

    在mysql5中遇到的问题: Illegal mix of collations (utf8_general_ci,IMPLICIT) and (utf8_unicode_ci,IMPLICIT) f ...

  4. MD5的加密和解密(总结)

    效果图例如以下: package com.test; import java.security.MessageDigest; public class MD5 { // MD5加码.32位 publi ...

  5. LCM Cardinality

    http://acm.hust.edu.cn/vjudge/contest/view.action?cid=31675#problem/E 暴力 // File Name: uva10892.cpp ...

  6. xcode Simulated Metrics xib设置小问题

  7. django-rest-framework 快速开始

    搭建项目 # Set up a new project django-admin.py startproject tutorial cd tutorial # Create a virtualenv ...

  8. jsp 有哪些动作?作用分别是什么?

    答:JSP 共有以下 6 种基本动作jsp:include: 在页面被请求的时候引入一个文件.jsp:useBean: 寻找或者实例化一个 JavaBean.jsp:setProperty: 设置 J ...

  9. c#操作MySQL数据库中文出现乱码(很多问号)的解决方法

    前题:修改discuz论坛帖子老连接(从NT版转到PHP版的discuzX3),帖子里有很多引用,有链接都是.aspx这样的链接. 需要将这些链接改到当前论坛的链接. 思路:用asp.net程序获取含 ...

  10. codeforces 620F. Xors on Segments

    题目链接 定义一种操作f(u, v) = u^u+1^.......^v. (u<=v), 给n个数, q个询问, 每个询问给出一个区间[l, r], 求这个区间里的f(a[i], a[j]) ...