Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to marshal int* in C#?

I would like to call this method in unmanaged library:

void __stdcall GetConstraints(

  unsigned int* puiMaxWidth,

  unsigned int* puiMaxHeight,

  unsigned int* puiMaxBoxes

);

My solution:

  • Delegate definition:

    [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void GetConstraintsDel(UIntPtr puiMaxWidth, UIntPtr puiMaxHeight, UIntPtr puiMaxBoxes);

  • The call of the method:

    // PLUGIN NAME
    GetConstraintsDel getConstraints = (GetConstraintsDel)Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall, typeof(GetConstraintsDel));
    
     uint maxWidth, maxHeight, maxBoxes;
    
     unsafe
     {
        UIntPtr a = new UIntPtr(&maxWidth);
        UIntPtr b = new UIntPtr(&maxHeight);
        UIntPtr c = new UIntPtr(&maxBoxes);
        getConstraints(a, b, c);
     }
    

It works but I have to allow "unsafe" flag. Is there a solution without unsafe code? Or is this solution ok? I don't quite understand the implications of setting the project with unsafe flag.

Thanks for help!

like image 851
Martin Vseticka Avatar asked Apr 28 '10 20:04

Martin Vseticka


1 Answers

Just out uint?

ie:

HRESULT GetTypeDefProps (
   [in]  mdTypeDef   td,
   [out] LPWSTR      szTypeDef,
   [in]  ULONG       cchTypeDef,
   [out] ULONG       *pchTypeDef,
   [out] DWORD       *pdwTypeDefFlags,
   [out] mdToken     *ptkExtends
);

works fine with:

uint GetTypeDefProps
(
  uint td, 
  [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=2)]char[] szTypeDef, 
  uint cchTypeDef, 
  out uint pchTypeDef, 
  out uint pdwTypeDefFlags, 
  out uint ptknds
 );

Sample use;

char[] SzTypeDef;
uint CchTypeDef;
uint PchMember;
IntPtr PpvSigBlob;
uint PbSigBlob;

  SzTypeDef= new char[500];
  CchTypeDef= (uint)SzTypeDef.Length;

ResPT= 
  MetaDataImport.GetTypeDefProps
  (
    td, 
    SzTypeDef, 
    CchTypeDef, 
    out pchTypeDef, 
    out pdwTypeDefFlags,
    out ptkExtends
  );
like image 125
Daniel Dolz Avatar answered Sep 27 '22 16:09

Daniel Dolz