Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

How to: Modify Reference Class in a Native Function

You can pass a reference class with a CLR array to a native function, and modify the class, using PInvoke services.

Compile the following native library.

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

struct S {
   wchar_t* str;
   int intarr[2];

extern "C"  {
   __declspec(dllexport) int bar(S* param) {
      printf_s("str: %S\n", param->str);
      printf_s("In native: intarr: %d, %d\n",
                param->intarr[0], param->intarr[1]);
      return 0;

Compile the following assembly.

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

[StructLayout(LayoutKind::Sequential, CharSet = CharSet::Unicode)]
ref class S  {
   String ^ str;
        ArraySubType=UnmanagedType::I4, SizeConst=2)]
   array<Int32> ^ intarr;

int bar([In][Out] S ^ param);

int main() {
   S ^ param = gcnew S;
   param->str = "Hello";
   param->intarr = gcnew array<Int32>(2);
   param->intarr[0] = 100;
   param->intarr[1] = 200;
   bar(param);   // Call to native function
   Console::WriteLine("In managed: intarr: {0}, {1}",
                       param->intarr[0], param->intarr[1]);
str: Hello In native: intarr: 100, 200 In managed: intarr: 300, 400

Community Additions

© 2015 Microsoft