Calling C++ function using DllImport

冷暖自知 提交于 2020-01-15 03:32:05

问题


This one is basic, how do I call the function SubscribeNewsFeed in the following from a C# DllImport?

class LogAppender : public L_Append
{
public:
    LogAppender()
        : outfile("TestLog.txt", std::ios::trunc | std::ios::out)
        , feedSubscribed(false)
    {
        outfile.setf(0, std::ios::floatfield);
        outfile.precision(4);
    }



    void SubscribeNewsFeed()
    {
        someOtherCalls();
    }

};

I'm unable to figure out how to include the class name when using the DllImport in my C# program here:

 class Program
    {

        [DllImport("LogAppender.dll")]
        public static extern void SubscribeNewsFeed();

        static void Main(string[] args)
        {
            SubscribeNewsFeed();
        }
    }

回答1:


PInvoke cannot be used to call directly into a C++ function in this way. Instead you need to define an extern "C" function which calls the PInvoke function and PInvoke into that function. Additionally you cannot PInvoke into a class instance method.

C / C++ Code

extern "C" void SubscribeNewsFeedHelper() {
  LogAppender appender;
  appender.SubscribeNewsFeed();
}

C#

[DllImport("LogAppender.dll")]
public static extern void SubscribeNewsFeedHelper();



回答2:


P/Invoke doesn't work that way. It only can import C functions. So there are different types of interop between the managed (C#) and native (C++) world. Interop via COM would be a solution - providing a C interface another.



来源:https://stackoverflow.com/questions/7955734/calling-c-function-using-dllimport

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!