gpt4 book ai didi

c# - 在 C# 中绑定(bind) C++ dll 时出现 EntryPointNotFoundException

转载 作者:可可西里 更新时间:2023-11-01 08:54:48 31 4
gpt4 key购买 nike

我尝试绑定(bind)一个简单的 c++ dll,如 http://msdn.microsoft.com/en-us/library/ms235636.aspx 所示。在我的 c# 控制台应用程序中,但我在运行时在 dll 中添加了一个 EntryPointNotFoundException。我的测试类是

namespace BindingCppDllExample
{
public class BindingDllClass
{
[DllImport("MathFuncsDll.dll")]
public static extern double Add(double a, double b);
}

public class Program
{
public static void Main(string[] args)
{
double a = 2.3;
double b = 3.8;
double c = BindingDllClass.Add(a, b);

Console.WriteLine(string.Format("{0} + {1} = {2}", a, b, c));
}
}
}

哪里不对?

最佳答案

您可以尝试在类外部声明函数,并使用 extern "C" 导出它们:

标题:

// MathFuncsDll.h
namespace MathFuncs
{
// Returns a + b
extern "C" __declspec(dllexport) double Add(double a, double b);

// Returns a - b
extern "C" __declspec(dllexport) double Subtract(double a, double b);

// Returns a * b
extern "C" __declspec(dllexport) double Multiply(double a, double b);

// Returns a / b
// Throws DivideByZeroException if b is 0
extern "C" __declspec(dllexport) double Divide(double a, double b);
}

实现:

// MyMathFuncs.cpp
#include "MathFuncsDll.h"
#include <stdexcept>

using namespace std;

namespace MathFuncs
{
double Add(double a, double b)
{
return a + b;
}

double Subtract(double a, double b)
{
return a - b;
}

double Multiply(double a, double b)
{
return a * b;
}

double Divide(double a, double b)
{
if (b == 0)
{
throw new invalid_argument("b cannot be zero!");
}

return a / b;
}
}

调用代码:

namespace BindingCppDllExample
{
public class BindingDllClass
{
[DllImport("MathFuncsDll.dll")]
public static extern double Add(double a, double b);
}

public class Program
{
public static void Main(string[] args)
{
double a = 2.3;
double b = 3.8;
double c = BindingDllClass.Add(a, b);

Console.WriteLine(string.Format("{0} + {1} = {2}", a, b, c));
}
}
}

关于c# - 在 C# 中绑定(bind) C++ dll 时出现 EntryPointNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12892271/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com