C#:DLLImport - DLL Not Found异常

时间:2013-05-21 05:12:45

标签: c# c++ gcc dllimport

假设我想从c#代码调用c ++函数,我遇到以下问题:

案例1:

class abc
{
private :
    int a ;

public :
    int  getValue()
    {
        return 100;
    }
};

int GetCounter()
{
    abc* p = new abc();

    int i = p->getValue();
    return i;
}

这种情况从C#调用函数时会抛出一个未找到DLL的异常。

案例2:

int GetCounter()
{
    int i = 333;
    return i;
}

从C#调用函数的情况很好。

任何想法为什么?我该如何解决?

1 个答案:

答案 0 :(得分:0)

在CPP项目中使用此示例代码行(MathFuncsDll.h)

extern "C" __declspec(dllexport) double Add(double a, double b);
extern "C" __declspec(dllexport) double Sub(double a, double b);
extern "C" __declspec(dllexport) double Mul(double a, double b);
extern "C" __declspec(dllexport) double Div(double a, double b);

在C#代码中使用像这样

 [DllImport("MathFuncs.dll", CallingConvention = CallingConvention.Cdecl)]
 public static extern Double Add(Double a, Double b);

 [DllImport("MathFuncs.dll", CallingConvention = CallingConvention.Cdecl)]
 public static extern Double Mul(Double a, Double b);

 [DllImport("MathFuncs.dll", CallingConvention = CallingConvention.Cdecl)]
 public static extern Double Sub(Double a, Double b);

 [DllImport("MathFuncs.dll",CallingConvention = CallingConvention.Cdecl)]
 public static extern Double Div(Double a, Double b);

 [DllImport("MathFuncs.dll",CallingConvention = CallingConvention.Cdecl)]
 public static extern Double Bat(Double a, Double b);