在我包含的 .dll 中找不到函数(funcPtr == 0)。我假设函数的名称在内部以某种方式被编码或更改,但我自己还无法弄清楚。
程序:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace Lab1Dynamic
{
class Program
{
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Ansi)]
static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)]string lpFileName);
[DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32", SetLastError = true, EntryPoint = "GetProcAddress")]
static extern IntPtr GetProcAddressOrdinal(IntPtr hModule, IntPtr procName);
private delegate double fDelegate(double x, double y);
static void Main(string[] args)
{
var dllPath = "MyLibrary.dll";
IntPtr dllInstance = LoadLibrary(dllPath);
while (dllInstance == IntPtr.Zero)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Can't load DLL " + dllPath);
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine("Write the path below...");
dllPath = Console.ReadLine();
dllInstance = LoadLibrary(dllPath);
}
string fname = "f";
IntPtr funcPtr = GetProcAddress(dllInstance, fname);
fDelegate fd = (fDelegate)Marshal.GetDelegateForFunctionPointer(funcPtr,
typeof(fDelegate));
var y = fd(1.0, 2.0);
}
}
}
dll:
using System;
namespace MyProj
{
public class MyLibrary
{
public static double f(double x, double y) => 3 * Math.Sin(x) + 2 * Math.Cos(y);
}
}
DLL(C++,VS2019):MyLib.h:
#pragma once
extern "C" __declspec(dllexport) double f(const double x, const double y);
MyLib.cpp:
#include "MyLib.h"
#include "pch.h"
#include <cmath>
double f(const double x, const double y)
{
return 3 * sin(x) + 2 * cos(y);
}
PS根据MDSN的指南here
您应该注意的第一件事是您的项目中使用了哪种约定:
接下来,在形成非托管导入函数的委托时,您需要添加适当的属性:
接下来,在请求指向非托管函数的指针时,请确保传递正确的函数名称:
就我而言:
还要确保项目的位深度匹配,即 如果库是 x86,那么项目在 c# x86 中,与 x64 相同。
以下是更正后的代码:
这是程序的实际输出: