apo*_*pse 6 c# dllimport loadlibrary
我有外部.DLL文件,里面有快速汇编程序代码.调用此.DLL文件中的函数以获得最佳性能的最佳方法是什么?
小智 11
您的DLL可能是python或c ++,无论如何,请执行相同的操作.
这是您在C++中的DLL文件.
标题:
extern "C" __declspec(dllexport) int MultiplyByTen(int numberToMultiply);
Run Code Online (Sandbox Code Playgroud)
源代码文件
#include "DynamicDLLToCall.h"
int MultiplyByTen(int numberToMultiply)
{
int returnValue = numberToMultiply * 10;
return returnValue;
}
Run Code Online (Sandbox Code Playgroud)
看看下面的C#代码:
static class NativeMethods
{
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr hModule);
}
class Program
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int MultiplyByTen(int numberToMultiply);
static void Main(string[] args)
{
IntPtr pDll = NativeMethods.LoadLibrary(@"PathToYourDll.DLL");
//oh dear, error handling here
//if (pDll == IntPtr.Zero)
IntPtr pAddressOfFunctionToCall = NativeMethods.GetProcAddress(pDll, "MultiplyByTen");
//oh dear, error handling here
//if(pAddressOfFunctionToCall == IntPtr.Zero)
MultiplyByTen multiplyByTen = (MultiplyByTen)Marshal.GetDelegateForFunctionPointer(
pAddressOfFunctionToCall,
typeof(MultiplyByTen));
int theResult = multiplyByTen(10);
bool result = NativeMethods.FreeLibrary(pDll);
//remaining code here
Console.WriteLine(theResult);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 3
我认为 DLLImport 和 LoadLibrary 有不同的目标。如果您使用本机 .dll,则应使用 DllImport。如果您使用 .NET 程序集,则应该使用 LoadAssembly。
实际上,您也可以动态加载本机程序集,请参阅此示例: dynamic-calling-an-unmanaged-dll-from-.net
归档时间: |
|
查看次数: |
31054 次 |
最近记录: |