Venryx
Venryx

Reputation: 17959

What is the equivalent of C#'s Marshal.PtrToStructure and StructureToPtr in node-ffi?

The C# functions are described below.

Marshal.PtrToStructure: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.marshal.ptrtostructure

Marshals data from an unmanaged block of memory to a managed object.

Parameters ptr (IntPtr): A pointer to an unmanaged block of memory.

structure (Object): The object to which the data is to be copied. This must be an instance of a formatted class.

Marshal.StructureToPtr: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.marshal.structuretoptr

Marshals data from a managed object to an unmanaged block of memory.

Parameters structure (Object): A managed object that holds the data to be marshaled. This object must be a structure or an instance of a formatted class.

ptr (IntPtr): A pointer to an unmanaged block of memory, which must be allocated before this method is called.

Upvotes: 0

Views: 776

Answers (1)

Venryx
Venryx

Reputation: 17959

While I don't know of a general-purpose function that's as easy to use as Marshal.PtrToStructure/StructureToPtr, I did figure out a lower-level way of accomplishing the same sort of thing: https://stackoverflow.com/a/58473299/2441655

Summary: Find/create a node-ffi Buffer that directly points to the struct-data in unmanaged memory, then:

  • To read: Set the Buffer's type field appropriately, then call deref().
  • To write: Call buffer.writeUInt32LE, with the offset of the given field supplied.

Upvotes: 1

Related Questions