Search code examples
javac++java-native-interface

How to obtain individual strings returned from GetPrivateProfileSection()


I normally use Java for programming. I have only basic knowledge of C++. I am currently using JNI to call the Windows API GetPrivateProfileSection().

I understand that I have to write a C++ function to do this. I am vaguely familiar with how to do this. The problem I face is the returned C++ string from GetPrivateProfileSection().

From the Microsoft documentation, I understand that the returned string contains name=value pairs each separated by a NULL character. The last name=value pair ends with 2 NULL characters.

What I want to do is to collect all the individual name=value strings and put them in an array. I have absolutely no clue as to how to do this with the returned string from GetPrivateProfileSection(). I have heard that I need to do something known as pointer arithmetics but I have no knowledge how to do this.

Could anyone help me out? Thanks!


Solution

  • The code that reads INI file to std::map looks like this:

    LPTSTR str_settings = new TCHAR[bufferSize];
    
    ::GetPrivateProfileSection(_T("MySection"), str_settings , bufferSize, _T("MyIni.ini"));
    
    std::map<std::string, std::string> settings; // map key -> value from ini file
    std::string sett_string;
    
    for (;*str_settings; str_settings += sett_string.length() + 1)
    {
       sett_string = str_settings;
    
       size_t pos = sett_string.find('=');
       std::string key;
       std::string value;
    
       if (pos == std::string::npos)
       {
          key = sett_string;
       }
       else
       {
          key.assign(sett_string.begin(), sett_string.begin() + pos);
          value.assign(sett_string.begin() + pos + 1, sett_string.end());
       }
    
       settings[key] = value;
    }