C# 中静态调用C++dll 和C# 中动态调用C++dll

简介:

在最近的项目中,牵涉到项目源代码保密问题,由于代码是C#写的,容易被反编译,因此决定抽取核心算法部分使用C++编写,C++到目前为止好像还不能被很好的反编译,当然如果你是反汇编高手的话,也许还是有可能反编译。这样一来,就涉及C#托管代码与C++非托管代码互相调用,于是调查了一些资料,顺便与大家分享一下:

一. C# 中静态调用C++动态链接

 

    1. 建立VC工程CppDemo,建立的时候选择Win32 Console(dll),选择Dll。

    2. 在DllDemo.cpp文件中添加这些代码。


extern "C" __declspec(dllexport) int Add(int a,int b)
{
    
     
return a+b;
}

    3. 编译工程。

    4. 建立新的C#工程,选择Console应用程序,建立测试程序InteropDemo
    5. 在Program.cs中添加引用:using System.Runtime.InteropServices;

    6. 在pulic class Program添加如下代码: 

 


using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace InteropDemo
{
    
class Program
    {
        [DllImport(
"CppDemo.dll", EntryPoint = "Add", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]
        
public static extern int Add(int a, int b); //DllImport请参照MSDN

        
static void Main(string[] args)
        {
            Console.WriteLine(Add(
12));
            Console.Read();
        }
    }
}

   好了,现在您可以测试Add程序了,是不是可以在C# 中调用C++动态链接了,当然这是静态调用,需要将CppDemo编译生成的Dll放在DllDemo程序的Bin目录下

二. C# 中动态调用C++动态链接

 在第一节中,讲了静态调用C++动态链接,由于Dll路径的限制,使用的不是很方便,C#中我们经常通过配置动态的调用托管Dll,例如常用的一些设计模式:Abstract Factory, Provider, Strategy模式等等,那么是不是也可以这样动态调用C++动态链接呢?只要您还记得在C++中,通过LoadLibrary, GetProcess, FreeLibrary这几个函数是可以动态调用动态链接的(它们包含在kernel32.dll中),那么问题迎刃而解了,下面我们一步一步实验

    1.  将kernel32中的几个方法封装成本地调用类NativeMethod


using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace InteropDemo
{
    
public static class NativeMethod
    {
        [DllImport(
"kernel32.dll", EntryPoint = "LoadLibrary")]
        
public static extern int LoadLibrary(
            [MarshalAs(UnmanagedType.LPStr)] 
string lpLibFileName);

        [DllImport(
"kernel32.dll", EntryPoint = "GetProcAddress")]
        
public static extern IntPtr GetProcAddress(int hModule,
            [MarshalAs(UnmanagedType.LPStr)] 
string lpProcName);

        [DllImport(
"kernel32.dll", EntryPoint = "FreeLibrary")]
        
public static extern bool FreeLibrary(int hModule);
    }
}

 

    2. 使用NativeMethod类动态读取C++Dll,获得函数指针,并且将指针封装成C#中的委托。原因很简单,C#中已经不能使用指针了,如下          
            int hModule = NativeMethod.LoadLibrary(@"c:"CppDemo.dll");

            IntPtr intPtr = NativeMethod.GetProcAddress(hModule, "Add");

详细请参见代码


using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace InteropDemo
{
    
class Program
    {
        
//[DllImport("CppDemo.dll", EntryPoint = "Add", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]
        
//public static extern int Add(int a, int b); //DllImport请参照MSDN


        
static void Main(string[] args)
        {
            
//1. 动态加载C++ Dll
            int hModule = NativeMethod.LoadLibrary(@"c:\CppDemo.dll");
            
if (hModule == 0return;

            
//2. 读取函数指针
            IntPtr intPtr = NativeMethod.GetProcAddress(hModule, "Add");

            
//3. 将函数指针封装成委托
            Add addFunction = (Add)Marshal.GetDelegateForFunctionPointer(intPtr, typeof(Add));

            
//4. 测试
            Console.WriteLine(addFunction(12));
            Console.Read();
        }

        
/// <summary>
        
/// 函数指针
        
/// </summary>
        
/// <param name="a"></param>
        
/// <param name="b"></param>
        
/// <returns></returns>
        delegate int Add(int a, int b);

    }
}

 

 

 

通过如上两个例子,我们可以在C#中动态或者静态的调用C++写的代码了.



本文转自夜&枫博客园博客,原文链接:http://www.cnblogs.com/newstart/archive/2012/10/24/2736780.html,如需转载请自行联系原作者

相关文章
|
10月前
|
C#
C# 解决引用dll,出现dll不可以使用等问题
C# 解决引用dll,出现dll不可以使用等问题
|
10月前
|
C++ 数据格式
LabVIEW传递接收C/C++DLL指针
LabVIEW传递接收C/C++DLL指针
262 1
|
6月前
|
物联网 C# C语言
物联网开发中C、C++和C#哪个更好用
在物联网(IoT)开发中,C、C++和C#各有优缺点,适用场景不同。C语言性能高、资源占用低,适合内存和计算能力有限的嵌入式系统,但开发复杂度高,易出错。C++支持面向对象编程,性能优秀,适用于复杂应用,但学习曲线陡峭,编译时间长。C#易于学习,与.NET框架结合紧密,适合快速开发Windows应用,但性能略低,平台支持有限。选择语言需根据具体项目需求、复杂性和团队技术栈综合考虑。
|
5月前
|
C#
Delphi可不可以制作出像c#那样的dll类库?
在Delphi中,创建DLL项目(如dll.dpr)并定义一个类TMyCls后,在另一个项目(如test.dpr)中可以引入此DLL并直接实例化和调用类的方法。然而,Delphi目前主要支持两种DLL形式:动态链接库(需显式声明exports,仅支持函数调用)和ActiveX DLL(需定义IDL接口)。这两种方式都较为繁琐。相比之下,C# 的DLL类库更为便捷,编写并编译后即可在其他项目中直接使用。
|
7月前
|
存储 C++
C++ dll 传 string 类 问题
C++ dll 传 string 类 问题
61 0
|
7月前
|
C#
C# WPF 将第三方DLL嵌入 exe
C# WPF 将第三方DLL嵌入 exe
140 0
|
7月前
|
C# 图形学 数据安全/隐私保护
Unity数据加密☀️ 二、使用Rider将C#代码生成DLL文件
Unity数据加密☀️ 二、使用Rider将C#代码生成DLL文件
|
9月前
|
Java Go C#
编程语言C#、C++、Java、Python、go 选择哪个好?
我想说的是,不论选择哪种编程语言,决定选择的都是你最终的目的,做选择之前,先充分调研每一个选择项,再做选择思路就会非常清晰了。
185 3
|
9月前
|
安全 编译器 API
程序与技术分享:C#调用DLL的几种方法
程序与技术分享:C#调用DLL的几种方法
380 0
|
9月前
|
程序员 C# C++
lpszBlogName C#开发多年中途被迫改行C++但工作中又经常偷偷使用C#的C++程序员
通过AUMID解析出packageFamily,再根据PackageManager解析出安装目录 PackageManager是WinRT的类型,如何在c++中使用WinRT,请参考C++/WinRT 以下代码需要管理员权限才能运行。