C# 请参阅指针指向的函数签名
我正在调用非托管dll。我这样做的方式是:C# 请参阅指针指向的函数签名,c#,pointers,dll,unmanaged,kernel32,C#,Pointers,Dll,Unmanaged,Kernel32,我正在调用非托管dll。我这样做的方式是: // Kernel functions used to load dll #region Kernell 32 [DllImport("kernel32")] static extern IntPtr LoadLibrary(string lpFileName); [DllImport("kernel32.dll")] static extern IntPtr GetProcAddress(IntPt
// Kernel functions used to load dll
#region Kernell 32
[DllImport("kernel32")]
static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32.dll")]
static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
#endregion
public void Test()
{
IntPtr dllHandle = LoadLibrary(@"C:\Program Files (x86)\SEGGER\JLinkARM_SDK_V484c\JLinkARM.dll");
// here is a function that enables me to read data from a chip
var ptr = GetProcAddress(loadedDllHandle, @"JLINK_HSS_Read");
{
Delegate1 readMem = (Delegate1)Marshal.GetDelegateForFunctionPointer(ptr, typeof(Delegate1));
// then if I want to read an integer from memory address 0x100 I will do
byte[] dataToRead = new byte[4];
unsafe
{
fixed (byte* fixedPointer = dataToRead)
{
// <----- FIRST CALL TO DLL WORKS GREAT!!!!!!!!!!!!!!!!
var retn = readMem(0x100, 4, (IntPtr)fixedPointer);
}
}
}
// there is another function called JLINK_HSS_Start
ptr = GetProcAddress(loadedDllHandle, @"JLINK_HSS_Start");
{
Delegate2 x = (Delegate2)Marshal.GetDelegateForFunctionPointer(ptr, typeof(Delegate1));
unsafe
{
var m = x(5); // here I get an exception!
}
}
}
//用于加载dll的内核函数
#区域克内尔32
[DllImport(“内核32”)]
静态外部IntPtr加载库(字符串lpFileName);
[DllImport(“kernel32.dll”)]
静态外部IntPtr GetProcAddress(IntPtr hModule,string procedureName);
#端区
公开无效测试()
{
IntPtr dllHandle=LoadLibrary(@“C:\Program Files(x86)\SEGGER\JLinkARM\u SDK\u V484c\JLinkARM.dll”);
//这里有一个函数,使我能够从芯片读取数据
var ptr=GetProcAddress(loadedDllHandle,@“JLINK\u HSS\u Read”);
{
Delegate1 readMem=(Delegate1)Marshal.GetDelegateForFunctionPointer(ptr,typeof(Delegate1));
//然后,如果我想从内存地址0x100中读取一个整数,我会这样做
字节[]数据读取=新字节[4];
不安全的
{
固定(字节*固定指针=数据读取)
{
//您需要查看SDK随附的头文件。需要注意的一点是调用约定。您可能需要将[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
添加到您的代理中,如果在需要时不这样做,将导致此错误(参数错误也是如此).您的第二次通话中有一个输入错误:
Delegate2 x = (Delegate2)Marshal.GetDelegateForFunctionPointer(ptr, typeof(Delegate1));
您正在传递Delegate1的类型,然后将其强制转换为Delegate2