Comment : modifier la classe de référence dans une fonction native
Vous pouvez passer une classe de référence avec un tableau CLR à une fonction native et modifier la classe à l’aide des services PInvoke.
Exemples
Compilez la bibliothèque native suivante.
// 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);
fflush(stdin);
fflush(stdout);
printf_s("In native: intarr: %d, %d\n",
param->intarr[0], param->intarr[1]);
fflush(stdin);
fflush(stdout);
param->intarr[0]=300;param->intarr[1]=400;
return 0;
}
};
Compilez l’assembly suivant.
// 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 {
public:
[MarshalAsAttribute(UnmanagedType::LPWStr)]
String ^ str;
[MarshalAsAttribute(UnmanagedType::ByValArray,
ArraySubType=UnmanagedType::I4, SizeConst=2)]
array<Int32> ^ intarr;
};
[DllImport("modify_ref_class_in_native_function.dll",
CharSet=CharSet::Unicode)]
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
Voir aussi
Commentaires
https://aka.ms/ContentUserFeedback.
Bientôt disponible : Tout au long de 2024, nous allons supprimer progressivement GitHub Issues comme mécanisme de commentaires pour le contenu et le remplacer par un nouveau système de commentaires. Pour plus d’informations, consultezEnvoyer et afficher des commentaires pour