如何使用DLL调用C#中C ++类的成员函数?

时间:2018-11-15 10:21:22

标签: c# c++ dll c++-cli

我在C ++中有一个导出函数,该函数返回指向类的指针。 我想在C#中捕获指针对象,并调用该指针所属类的关联成员函数。

// C++: Test.h
class Test
{
public:
    int f1();
    std::string f2();
    std::vector<std::string> f3();
private:
    int m1;
    std::string m2;
    std::vector<std::string> m3;
};

现在我有一个导出函数,该函数将指针返回到Test类的对象。

extern "C" __declspec(dllexport) Test * getTestInst();

当我在C#中调用上述函数并尝试访问Test类的成员时,出现错误。 //错误:CS1061'IntPtr'不包含'f2'的定义,并且找不到扩展方法'f2'接受类型为'IntPtr'的第一个参数

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;

namespace SampleClient
{
    class Program
    {
        [DllImport("TESTLIBRARY.dll")]
        static public extern IntPtr getTestInst();

        static void Main(string[] args)
        {
            string data;
            IntPtr pTest = getTestInst();
            data = pTest.f2();      // Error : CS1061   'IntPtr' does not contain a definition for 'f2' and no extension method 'f2' accepting a first argument of type 'IntPtr' could be found

            Console.WriteLine("Data {0}", data);
        }
    }
}

请帮助我使用代码访问C#中C ++类对象的成员函数。

0 个答案:

没有答案