How can I call a function of a C++ DLL that accepts a parameter of type stringstream from C#?

后端 未结 5 1138
死守一世寂寞
死守一世寂寞 2020-12-02 00:43

I want to import an unmanaged C++ DLL and call a function that takes stringstream as a parameter. In C#, there is no stringstream class, so can any

相关标签:
5条回答
  • 2020-12-02 00:51

    You are trying to bind native C++ code to managed code in C#. Best way of doing that in general is to introduce middle layer in managed C++ that will provide interface to calls from C#.

    0 讨论(0)
  • 2020-12-02 00:59

    You should not expose templated objects via a DLL, period.

    Templated objects (e.g. almost everything in std::) become inlined. So in this way, your DLL gets its own private copy of the implementation. The module calling your DLL will also get its own private implementation of stringstream. Passing between them means you are inadvertently weaving two unrelated implementations together. For many projects, if you are using the exact same build settings, it's probably no problem.

    But even if you use the same compiler, and mix a release DLL with a debug EXE, you will find stack / heap corruption and other harder-to-find problems.

    And that's only using your DLL from another unmanaged C++ exe/dll. Crossing then the lines to .NET is even more of a problem.

    The solution is to change your DLL's interface to something that plays friendly across DLL bounds. Either COM (you could use IStream for example), or just a C-style interface like the winapi.

    0 讨论(0)
  • 2020-12-02 01:04

    Create an Wrapper dll in c, or c++ that exposes an friendly call to that function. It's the better way.

    for example an

    BOOL getString(TCHAR * myreturnString, DWORD *size);
    
    0 讨论(0)
  • 2020-12-02 01:07

    I'm afraid that you're going to have to create your own StringStream class in C# in order to be able to consume the functions exported from that DLL. As you mentioned, the .NET Framework doesn't provide any similar class out of the box.

    The easiest way is probably to wrap the StringBuilder class provided by the .NET Framework such that it can function as a stream. See this blog post for a further explanation and some sample code.

    A similar question was also answered in MSDN Magazine: http://msdn.microsoft.com/en-us/magazine/cc163768.aspx. You might find some of the hints and/or sample code given there useful.

    0 讨论(0)
  • 2020-12-02 01:10

    If you can modify the C++ dll, export a plain string version. Otherwise you have to build a managed C++ wrapper project, import the other C++ dll, export it as a managed function, and call that from your C# code. C++ interop really sucks.

    0 讨论(0)
提交回复
热议问题