本文介绍了使用pinvoke从C#调用非托管C ++代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个不受管理的C ++ dll,我无法访问其代码,但具有所有方法的声明。

I have a unmanaged C++ dll for which I do not have access to code but have all methods declarations for.

为了简单起见,.h看起来像这样:

Lets for simplicity say that .h looks like this:

#include <iostream>

#ifndef NUMERIC_LIBRARY
#define NUMERIC_LIBRARY

class Numeric
{
    public:
        Numeric();
        int Add(int a, int b);
        ~Numeric();
};

#endif

.cpp文件中的方法实现

and method implementation in .cpp file

int Numeric::Add(int a, int b)
{
    return (a + b);
}

我只是想在C#代码中从C ++调用add函数:

I simply want to call the add function from C++ in my C# code:

namespace UnmanagedTester
{
    class Program
    {
        [DllImport(@"C:\CPP and CSharp Project\UnmanagedNumeric\Debug\numeric.dll", EntryPoint = "Add")]
        public static extern int Add(int a, int b);


        static void Main(string[] args)
        {
            int sum = Add(2, 3);
            Console.WriteLine(sum);

        }
    }
}

尝试后执行我有以下错误:

After trying to execute I have the following error:

在DLL'C:\CPP和CSharp Project\UnmanagedNumeric\Debug中找不到名为'Add'的入口点mericnumeric.dll'。

Unable to find an entry point named 'Add' in DLL 'C:\CPP and CSharp Project\UnmanagedNumeric\Debug\numeric.dll'.

我无法更改C ++代码。不知道出了什么问题。
感谢您的帮助。

I CAN NOT change C++ code. Have no idea what is going wrong.Appreciate your help.

推荐答案

使用PInvoke只能调用从Dll导出的全局函数。要使用导出的C ++类,您需要编写C ++ / CLI包装器。这是C ++ / CLI类库项目,它公开了纯.NET接口,在内部与非托管C ++ Dll链接,从该Dll实例化一个类并调用其方法。

Using PInvoke you can only call global functions exported from Dll. To use exported C++ classes, you need to write C++/CLI wrapper. This is C++/CLI Class Library project, which exposes pure .NET interface, internally it is linked to unmanaged C++ Dll, instantiates a class from this Dll and calls its methods.

编辑:您可以从以下位置开始:

you can start from this: http://www.codeproject.com/KB/mcpp/quickcppcli.aspx#A8

这篇关于使用pinvoke从C#调用非托管C ++代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 07:20