Ptr to a Structure?

Is there an easy way to get a Pointer (Ptr) to a structure for use in declares?
I’ve been using an intermediate memory block which seems inelegant:

  dim s as MY_STRUCTURE
  s.foobar=123
 dim m as memoryblock = s.StringValue(true)
 dim p as Ptr = m
 ... then, use p when calling a declare

Are you sure that the function is really requesting a pointer to a structure and not a structure?
Can you post your declare?

I’m asking in general here, and, yes, it requires a pointer.

ByRef

You may be right.

This doesn’t work:

  declare function GdipBitmapUnlockBits lib  "GDIPlus" (bitmap as Ptr, bitmapData as Ptr) as integer
  dim sBitmap as BITMAP
  dim sBitmapData as BitmapData
  dim r as integer = GdipBitmapUnlockBits(sBitmap,sBitmapData)

but this compiles without error:

  declare function GdipBitmapUnlockBits lib  "GDIPlus" (byref bitmap as BITMAP, byref bitmapData as BitmapData) as integer
  dim sBitmap as BITMAP
  dim sBitmapData as BitmapData
  dim r as integer = GdipBitmapUnlockBits(sBitmap,sBitmapData)

Have you done this before and verified that the correct pointers are being passed?

I’ve asked for better documentation here: <https://xojo.com/issue/34148>

ByRef is correct. When an external function expects a pointer to a piece of data, you can declare the parameter as a generic Ptr, or you can declare it ByRef as the desired type. Either way, you are telling the compiler that the external function expects a pointer to some data. If the intent is that the function will modify the data before returning, ByRef is probably the right choice.

This is true for all types, structures or otherwise: you can either create a memoryblock with the right size, populate it, and pass the memoryblock’s pointer to the external function; or you can declare the external function using a ByRef parameter of the appropriate type and pass in the value directly. Either way, the compiler will generate code which gets a pointer to the bit of memory you’ve named and passes it along to the external function.

Thanks, that’s handy to know and will simplify some ugly-looking code :slight_smile:

I’ve just run into this too and it’s was very helpful to look here in the forum!

1 Like