开发者

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:

    // 开发者_如何学PythonPLUGIN 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!


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
  );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜