开发者

mixed programming for a string between C# managed code and c++ unmanaged code

开发者 https://www.devze.com 2023-03-24 20:49 出处:网络
I\'m working on a c++ project which uses a string path to call an XML file. When i compiled the c++ everything works perfectly and i\'m able to use the XML file as my project requires.

I'm working on a c++ project which uses a string path to call an XML file. When i compiled the c++ everything works perfectly and i'm able to use the XML file as my project requires.

I needed to use a C# GUI, so i made a wrapper to call all my functions from my C++ file. One problem arises after debugging between the both platforms, c# does not recognize the string path to call my file, the error that i got is that it can not find the given path. Does anyone know how to send a valid string path between both platforms?

Thanks in advance, Carolina

    int ClassUnmanaged::ReadFile(string path_to_file)
 开发者_Go百科    {
        int status = XMLClass->ReadConfigFile(path_to_file);

        if(status)
        {
           return status; //Error
        }

        else
        {
           return 0;
        }
    }

Wrapper.h for the C++ class

    public __gc class Wrapper
    {

      public:   Wrapper(void);
      public:   ~Wrapper(void);
             /** Unmanaged pointer to Class Unmanaged API
               *    
               */
      private:  ClassUnmanaged__nogc* pointerUnmanaged;

          public: int NewReadfile(string path_to_file);
    }

Wrapper.cpp

    int Wrapper::NewReadFile(string path)
    {
        pointerUnmanaged->ReadFile(path);//here i access to my class unmanaged
    return 0;
     }

UI.cs

In the UI.cs i can not call the function NewReadfile from the wrapper because of the string type that c++ uses. Any idea how to solve this?


You will need to change the NewReadFile method to public and then change it to take as input a type that C# know about like Sytem::String it should look like this (using the new managed C++ syntax adapt to the old one if needed)

int Wrapper::NewReadFile(System::String^ path)
{
    char* pathAsCharArray = (char*)(void*)Marshal::StringToHGlobalAnsi(str);
    try
    {
        std::string pathAsStdString(pathAsCharArray);
        pointerUnmanaged->ReadFile(pathAsStdString);
    }
    finally
    {
        Marshal::FreeHGlobal(pathUnmanaged);
    }

    return 0;
 }

There is a KB article named "How to convert from System::String* to Char* in Visual C++" that explain the concept. If your underlying API could support unicode and you use the new syntax a better way to do the conversion is something like :

pin_ptr<const wchar_t> pathAsCharArray = PtrToStringChars(path);
std::wstring pathAsStrign(pathAsCharArray);
0

精彩评论

暂无评论...
验证码 换一张
取 消