Export (0) Print
Expand All

How to: Modify System::String in Native Function Using PInvoke 

Visual Studio 2005

You can pass an array of String to a native function and modify the array in the native function using PInvoke services with DllImportAttribute and MarshalAsAttribute.

Example

Compile the native library.

// string_in_native_function.cpp
// compile with: /LD
#include <stdio.h>
#include <windows.h>

extern "C" {
   __declspec(dllexport) int f(wchar_t* buff[]) {
      printf_s("in f: %S\n", buff[0]);
      fflush(stdin);
      fflush(stdout);
      buff[0] = L"changed";
      return wcslen(buff[0]);
   }
};

Compile the following assembly that consumes the native DLL.

// string_in_native_function_2.cpp
// compile with: /clr
using namespace System;
using namespace System::Runtime::InteropServices;

[DllImport("string_in_native_function.dll", CharSet=CharSet::Unicode)]
int f([In][Out][MarshalAsAttribute(UnmanagedType::LPArray, 
                ArraySubType=UnmanagedType::LPWStr, SizeConst=2)] array<String ^> ^ str);

int main() {
   array<String ^> ^ myarr = gcnew array<String^>(2);
   myarr[0] = "one";
   myarr[1] = "two";
   f(myarr);   // call to imported native function.
   Console::WriteLine("in managed: {0}", myarr[0]);
}

Output

in f: one
in managed: changed

See Also

Community Additions

ADD
Show:
© 2014 Microsoft