0

I have a simple C++ program which calls a C# DLL. It sends and receives a string.

#include "stdafx.h"
#include <string>
#include <msclr\marshal_cppstd.h>

char* callCsDLL(char* arg) {
    // arg will be passed to C# DLL method
    // and result will contain a string reply

    // Copy a new System::String^ from char*
    System::String^ clrString = msclr::interop::marshal_as<System::String^>(arg);

    // Call C# function
    System::String^ t = Namespace::Class::run(clrString);

    // Create new std::string from System::String^
    std::string cppString = msclr::interop::marshal_as<std::string>(t);

    // Copy C++ string to the result
    char* result = new char[cppString.length() + 1];
    strcpy(result, cppString.c_str()); 
    return result;
}

Inside Visual Studio 2017, this is quite easy to do, use C++ CLR, just add the C# DLL to the references in the C++ project, and build. It's almost magic.

How would I link these together outside of Visual Studio, that is, using the command line? Could I avoid MSBUILD altogether? The resulting executable should simply use the DLL.

V. V. Kozlov
  • 189
  • 2
  • 10
  • What do you mean _outside of Visual Studio_? Using MSBuild from the command line? – πάντα ῥεῖ Feb 26 '19 at 11:01
  • You haven't a native c++ program. You have an managed c++ program which uses a C# *.dll. Here's an explanation of the differences: https://stackoverflow.com/questions/114238/difference-between-managed-c-and-c So when you want to create a native c++ program I belive you have to write a COM wrapper around you C# *.dll and use it. – user743414 Feb 26 '19 at 12:17
  • Such is the trouble with magic, you first have to understand what you did before you can make such unrealistic demands. What you have *not* done is write any C++ code, linking it is indeed the wall that the approach crashes into at a hundred miles an hour. It is the worst possible way to do this kind of interop, don't follow the advice [in this post](https://stackoverflow.com/a/17131801/17034) before you looked at the other ways. Exporting the function is the crucial step. – Hans Passant Feb 26 '19 at 13:01

0 Answers0