在C#代码中调用C DLL

Call C++ dll in c# code

本文关键字:DLL 调用 代码      更新时间:2023-10-16

我试图在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:SourcesOperationsOnline.DevBINDebugMlt1090d64.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 inline.dev bin debug mlt1090d64.dll'。

问题是您尝试调用类成员方法。

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

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

并在.cs

中更新
[DllImport(@"C:SourcesOperationsOnline.DevBINDebugMlt1090d64.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int testfunc(int n);