[原创]C#引用C++编译的dll
一、DllImportAttribute
1、属性介绍
using System;
using System.Reflection;
using System.Security; namespace System.Runtime.InteropServices
{
// Summary:
// Indicates that the attributed method is exposed by an unmanaged dynamic-link
// library (DLL) as a static entry point.
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
[ComVisible(true)]
public sealed class DllImportAttribute : Attribute
{
// Summary:
// Enables or disables best-fit mapping behavior when converting Unicode characters
// to ANSI characters.
public bool BestFitMapping;
//
// Summary:
// Indicates the calling convention of an entry point.
public CallingConvention CallingConvention;
//
// Summary:
// Indicates how to marshal string parameters to the method and controls name
// mangling.
public CharSet CharSet;
//
// Summary:
// Indicates the name or ordinal of the DLL entry point to be called.
public string EntryPoint;
//
// Summary:
// Controls whether the System.Runtime.InteropServices.DllImportAttribute.CharSet
// field causes the common language runtime to search an unmanaged DLL for entry-point
// names other than the one specified.
public bool ExactSpelling;
//
// Summary:
// Indicates whether unmanaged methods that have HRESULT or retval return values
// are directly translated or whether HRESULT or retval return values are automatically
// converted to exceptions.
public bool PreserveSig;
//
// Summary:
// Indicates whether the callee calls the SetLastError Win32 API function before
// returning from the attributed method.
public bool SetLastError;
//
// Summary:
// Enables or disables the throwing of an exception on an unmappable Unicode
// character that is converted to an ANSI "?" character.
public bool ThrowOnUnmappableChar; // Summary:
// Initializes a new instance of the System.Runtime.InteropServices.DllImportAttribute
// class with the name of the DLL containing the method to import.
//
// Parameters:
// dllName:
// The name of the DLL that contains the unmanaged method. This can include
// an assembly display name, if the DLL is included in an assembly.
public DllImportAttribute(string dllName); // Summary:
// Gets the name of the DLL file that contains the entry point.
//
// Returns:
// The name of the DLL file that contains the entry point.
public string Value { get; }
}
}
2、举例
class BLApi
{
[DllImport(@"xx.dll", EntryPoint = "TWelcomeFace_Init", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]
public extern static Int32 TWelcomeFace_Init(string namingService, string localhost, string dvsService, string matchService);
}
3、引入依赖dll
将依赖dll添加到解决方案中,与主dll放在相同目录下(重要),然后设置dll的属性CopyToOutputDirectory= CopyAlways,编译器就会自动找到了。


二、应用LoadLibrary
1、封装基础类
public class DllInvoke
{
[DllImport("kernel32.dll")]
private extern static IntPtr LoadLibrary(String path);
[DllImport("kernel32.dll")]
private extern static IntPtr GetProcAddress(IntPtr lib, String funcName);
[DllImport("kernel32.dll")]
private extern static bool FreeLibrary(IntPtr lib);
[DllImport("kernel32.dll")]
private extern static int GetLastError();
private IntPtr hLib;
public DllInvoke(String dllPath, List<string> DependentDllPaths = null)
{
if(DependentDllPaths != null)
{
foreach (string dllName in DependentDllPaths)
{
IntPtr loadAuxiliary = LoadLibrary(dllName);
if (loadAuxiliary == IntPtr.Zero)
{
throw new Exception(dllName + "加载失败!");
}
}
}
hLib = LoadLibrary(dllPath);
}
~DllInvoke()
{
FreeLibrary(hLib);
} public Delegate Invoke(String APIName, Type t)
{
IntPtr api = GetProcAddress(hLib, APIName);
var s = Marshal.GetDelegateForFunctionPointer(api, t);
return (Delegate)s;
}
}
LoadLibrary引用的dll相关的依赖dll必须被手动引用进来,否则会报错。
2、举例
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi, SetLastError = true)]
delegate Int32 TWelcomeFace_Init(string Naming_Service, string Locale_Host, string DVS_Service, string Match_Service); class BLApi
{
private static DllInvoke _dll = new DllInvoke(@"xx.dll"); public static Int32 TWelcomeFace_Init(string namingService, string localhost, string dvsService, string matchService)
{
try
{
TWelcomeFace_Init dele = (TWelcomeFace_Init)_dll.Invoke("TWelcomeFace_Init", typeof(TWelcomeFace_Init));
Int32 result = dele(namingService, localhost, dvsService, matchService); return result;
}
catch (Exception ex)
{
throw ex;
}
}
}
[原创]C#引用C++编译的dll的更多相关文章
- 关于.Net中Process的使用方法和各种用途汇总(二):用Process启动cmd.exe完成将cs编译成dll
上一章博客我为大家介绍了Process类的所有基本使用方法,这一章博客我来为大家做一个小扩展,来熟悉一下Process类的实际使用,废话不多说我们开始演示. 先看看我们的软件要设计成的布局吧. 首先我 ...
- Unity插件之Unity调用C#编译的DLL
Unity插件分为两种:托管插件(Managed Plugins)和本地插件(Native Plugins).本文先来说说Unity中的托管插件,本地插件的文章留到下一篇文章再说. 有时候我们会有这样 ...
- Unity 代码编译成dll 更新dll实现热更代码
Unity 代码编译成dll 更新dll实现热更代码 实现流程 代码编译成DLL DLL打包成AssetBundle 加载AssetBundle 加载代码程序集 获取指定类 使用反射赋值 C#代码编译 ...
- 如何使用g++编译调用dll的c++代码
本文将有以下4个部分来讲如何使用g++编译调用dll的c++代码. 1.如何调用dll 2.动态链接和静态链接的区别 3.g++的编译参数以及如何编译调用dll的c++代码 4.总结 1.如何调用dl ...
- C#.NET常见问题(FAQ)-如何将cs文件编译成dll文件 exe文件 如何调用dll文件
比如我要把TestDLL.cs文件编译成dll文件,则在命令提示符下,输入下面的命令,生成的文件为TestDLL.dll csc /target:library TestDLL.cs 注意前提是你安装 ...
- 使用RazorGenerator和预编译MVC引擎将Razor视图编译成DLL
Web开发中常常会有跨页面.跨站点.跨项目组的复用模块(界面),最常见的就是如下方所示的Web页面上用于显示登录或用户名的头部模块, 使用ASP.NET MVC开发中,常见的做法是写成部分视图,本文的 ...
- Golang 编译成 DLL 文件
golang 编译 dll 过程中需要用到 gcc,所以先安装 MinGW. windows 64 位系统应下载 MinGW 的 64 位版本: https://sourceforge.net/pro ...
- asp.net源程序编译为dll文件并调用的实现过程
很多时候,我们需要将.cs文件单独编译成.dll文件,这就需要使用csc命令将.cs文件编译成.dll动态链接库文件.具体的操作步骤如下: 打开命令窗口->输入cmd到控制台->cd C: ...
- VC将同一份代码同时编译为Dll和Exe的方法
开发中经常遇到这样的情况,需要开发一个某某功能的接口Dll,但是Dll不能直接调试,你至少需要一个Loader 但是Loader和Dll本身不在同一个工程里,虽然都在本机的话并不影响源码级调试,但是总 ...
随机推荐
- linux块设备驱动之实例
1.注册:向内核注册个块设备驱动,其实就是用主设备号告诉内核这个代表块设备驱动 sbull_major = register_blkdev(sbull_major, "sbull&quo ...
- 面对对象之@classmethod、@staticmethod用法
@classmethod用法(修饰的函数,第一个参数cls默认是类名,调用方法:实例对象或类对象.方法) class C_mthod(object): name = "f**k" ...
- [转]表结构设计器EZDML介绍说明(包含修改配置文件,修改文本字段属性)
超轻量级的表结构设计工具,这是一个数据库建表的小软件,可快速的进行数据库表结构设计,建立数据模型.类似大家常用的数据库建模工具如PowerDesigner.ERWIN.ER-Studio和Ration ...
- 移动端js写法
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...
- ElasticSearch与Spring Boot集成问题
1.None of the configured nodes are available 或者 org.elasticsearch.transport.RemoteTransportException ...
- 附录1· 初识Linux操作系统
编译 GCC汇编器 NASM链接 LD调试 GDBBochsBochs模拟器微内核 单内核=====================Linux特点=====================以下所有内 ...
- unreal 自定义 Slate Style Sets
搜集到的最有价值的一篇教学,按照作者的方法尝试中遇到了一些问题.[感谢这位作者!] 网址:https://wiki.unrealengine.com/Slate_Style_Sets_Part_2 在 ...
- XAF视频教程来啦,已出15课
第一到第七课在这里: http://www.cnblogs.com/foreachlife/p/xafvideo_1_6.html 视频地址:http://i.youku.com/i/UMTI5OTE ...
- angularjs指令系统系列课程(2):优先级priority,模板template,模板页templateUrl
今天我们先对 priority,template,templateUrl进行学习 1.priority 可取值:int 作用:优先级 一般priority默认为0,数值越大,优先级越高.当一个dom元 ...
- jquery.trim() vs JS.trim()
如果你在IE8浏览器下开发网站,其实这是个假命题,因为原生的javascript 并不支持 .trim()方法,如果你写了类似document.getElementByID().trim();的代码, ...