[原创]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本身不在同一个工程里,虽然都在本机的话并不影响源码级调试,但是总 ...
随机推荐
- mybatis批量插入返回主键问题
今天整合mybatis时候用到返回主键问题,批量插入总是返回不了主键还报错. 记录入下: pom版本: <mybatis.version>3.2.6</mybatis.version ...
- jQuery选择器方式-用的不多的name选择器
id:$("#id") name:$("[name='name']") class:$(".class") element:$(" ...
- XMLHttpRequest简介
要真正实现这种绚丽的奇迹,必须非常熟悉一个 JavaScript 对象,即 XMLHttpRequest. 下面给出将要用于该对象的很少的几个 方法和属性. ·open():建立到服务器的新请求. · ...
- iOS10通知框架UserNotification理解与应用
iOS10通知框架UserNotification理解与应用 一.引言 关于通知,无论与远程Push还是本地通知,以往的iOS系统暴漏给开发者的接口都是十分有限的,开发者只能对标题和内容进行简单的定义 ...
- JS判断日期是否在同一个星期内,和同一个月内
今天要用到判断日期是否在同一个星期内和是否在同一个月内,在网上找了好一会儿也没找到合适的,然后自己写了一个方法来处理这个问题,思路就不详细介绍了,直接附上代码,自己测试了一下 没有问题,若有问题请在评 ...
- 我为开源做贡献,网页正文提取——Html2Article
为什么要做正文提取 一般做舆情分析,都会涉及到网页正文内容提取.对于分析而言,有价值的信息是正文部分,大多数情况下,为了便于分析,需要将网页中和正文不相干的部分给剔除.可以说正文提取的好坏,直接影响了 ...
- php 5.3新增的闭包语法介绍function() use() {}
* 下面提到的代码在PHP5.3以上版本运行通过. */function callback($callback) { $callback();}//输出: This is a anonymous fu ...
- java.lang.ExceptionInInitializerError /NoClassDefFoundError: [Lorg/hibernate/engine/FilterDefinition;
java.lang.ExceptionInInitializerError at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Nati ...
- 利用反卷积神经网络可视化CNN
http://blog.csdn.net/hjimce/article/details/51762046 http://arxiv.org/pdf/1311.2901.pdf Visualizing ...
- Openstack+Kubernetes+Docker微服务实践之路--Kubernetes
经过几番折腾终于搞定Kubernetes了,我们要在Openstack上部署Kubernetes集群,使用最新工具Kubeadm来安装,由于不能直接访问Kubernetes的源,我们需要一台可以穿墙的 ...