none
Calling C# function from c# dll in c++ RRS feed

  • Question

  • Hello,

    I HAVE A FUNCTION IN C# supposed to return a string.

    I want to call this function from c++ code which will receive this string in char* variable.

    I made dll of c# application.

    I am not getting what should I do next to call this function from c++?

    please reply ASAP.

    Thank You.

    Thursday, May 6, 2010 6:06 AM

Answers

  • int main()
    {
    System::String ^str = MyAssembly::MyAssembly::Test();

    System::IntPtr ptr = System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(str);
    char * buf = (char *)ptr.ToPointer();

    std::cout<<buf<<std::endl;

    Marshal::FreeHGlobal(ptr);

    return 0;
    }
    Monday, May 10, 2010 3:32 AM
  • Well, I should have put some comments on that.

    It's rather intuitive. MyAssembly is my test assembly written in C#, and Test() is a static method it exposed. The method returns a String value. And The Marshal::StringToHGlobalAnsi method takes the return string and copies the data from managed world to unmanaged world, and that's why you have to call Marshal::FreeHGlobal to free the memory after you finished using it.

    After we retrieved the pointer to the memory, we call ToPointer to retrieve the actual pointer (void *) to the memory and reinterpret it as a char *.

    Hope this helps.

    • Marked as answer by SamAgain Thursday, May 13, 2010 9:50 AM
    Monday, May 10, 2010 1:47 PM

All replies

  • Is this native C++ code or hare you using C++/CLI and managed code?
    Mattias, C# MVP
    Thursday, May 6, 2010 12:46 PM
    Moderator
  • It is managed c++ code.
    Friday, May 7, 2010 11:33 AM
  • int main()
    {
    System::String ^str = MyAssembly::MyAssembly::Test();

    System::IntPtr ptr = System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(str);
    char * buf = (char *)ptr.ToPointer();

    std::cout<<buf<<std::endl;

    Marshal::FreeHGlobal(ptr);

    return 0;
    }
    Monday, May 10, 2010 3:32 AM
  • Can you please explain each step?

     

    Monday, May 10, 2010 8:42 AM
  • Well, I should have put some comments on that.

    It's rather intuitive. MyAssembly is my test assembly written in C#, and Test() is a static method it exposed. The method returns a String value. And The Marshal::StringToHGlobalAnsi method takes the return string and copies the data from managed world to unmanaged world, and that's why you have to call Marshal::FreeHGlobal to free the memory after you finished using it.

    After we retrieved the pointer to the memory, we call ToPointer to retrieve the actual pointer (void *) to the memory and reinterpret it as a char *.

    Hope this helps.

    • Marked as answer by SamAgain Thursday, May 13, 2010 9:50 AM
    Monday, May 10, 2010 1:47 PM