【问题标题】:Call C++ dll in c# code在 C# 代码中调用 C++ dll
【发布时间】:2017-05-05 06:15:17
【问题描述】:

我正在尝试在 C# 代码中调用 C++ dll。 我的头文件 -

#define MLTtest __declspec(dllexport)
class MLTtest testBuilder
{
public:
    testBuilder(void);
    ~testBuilder(void);


    int testfunc (int iNumber);
};

我的 .CPP 课程

int testBuilder::testfunc (int iNumber)
{

    return iNumber*2 ;
}

这是我使用该 dll 的 C# 代码。

class Program
{

    [DllImport(@"C:\Sources\Operations\Online.Dev\BIN\Debug\Mlt1090d64.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "testfunc")]
    public static extern int testfunc(int n);

    static void Main(string[] args)
    {
        try
        {
            int x = testfunc (50);
        }
        catch (Exception ex)
        {
        }
    }
}

但我不断收到此异常异常:

无法在 DLL 中找到名为“testfunc”的入口点 'C:\Sources\Operations\Online.Dev\BIN\Debug\Mlt1090d64.dll'。

【问题讨论】:

  • 不,这不是我现在编辑的原因。它的复制粘贴错误在这里:)
  • @Adrian 响应是正确的......如果你真的想从 C# 调用 C++(但请注意,它很脆弱,很痛苦,最后它并不是真的有用),见stackoverflow.com/a/42552494/613130

标签: c# c++ dll


【解决方案1】:

问题是你试图调用一个类成员方法。

将流动函数(不是类成员)放在 .cpp 文件中

extern "C" int __declspec(dllexport) testfunc(int iNumber)
{
  return iNumber*2;
}

并在 .cs 中更新

[DllImport(@"C:\Sources\Operations\Online.Dev\BIN\Debug\Mlt1090d64.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int testfunc(int n);

【讨论】:

    猜你喜欢
    • 2012-09-06
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多