简体   繁体   English

在 Visual Works Smalltalk 中从 CPointer 创建 CByteArray

[英]Create a CByteArray from a CPointer in Visual Works Smalltalk

Some C function return aCPointer to a C struct .某些 C 函数将aCPointer返回到C struct The C struct is known. C struct是已知的。
Now i want to put the C struct into a ByteArray .现在我想将C struct放入ByteArray Basically copy the contents of the struct to a ByteArray .基本上将结构的内容复制到ByteArray
In GemStone/S this can be done with:GemStone/S 中,这可以通过以下方式完成:
CByteArray fromCPointer: aCPointer numBytes: 120.
"this create aCByteArray with the contents of the struct referenced by CPointer (copying only 120 bytes)" “这将使用 CPointer 引用的结构的内容创建一个 CByteArray(仅复制 120 个字节)”

Is there something similar on Visual Works ? Visual Works 上有类似的东西吗? I did not find it yet.我还没有找到。 It could be possible to replicate C struct at Visual Works level but is only one struct and it is ok to handle it at low level.可以在 Visual Works 级别复制 C 结构,但它只是一个结构,可以在低级别处理它。

There's only the rather ugly #copyAt:to:size:startingAt: that you can send to a pointer.只有相当丑陋的#copyAt:to:size:startingAt:可以发送到指针。 You need to allocate a ByteArray yourself (make sure it's big enough).您需要自己分配一个ByteArray (确保它足够大)。

answer := ByteArray new: size.
pointer
        copyAt: 0
        to: answer
        size: size
        startingAt: 1.

The other way (ByteArray -> Pointer) would be done using #copyAt:from:size:startingAt: .另一种方式(ByteArray -> Pointer)将使用#copyAt:from:size:startingAt:

This method works for both ByteArray and UninterpretedBytes .此方法适用于ByteArrayUninterpretedBytes If you want to read data from the bytes, UninterpretedBytes may be more helpful as you can send things like #longAt: to read a long from an offset.如果您想从字节中读取数据, UninterpretedBytes可能会更有帮助,因为您可以发送诸如#longAt:来从偏移量中读取long

If aCPointer points to a struct of char * for example:如果aCPointer指向一个 char * 结构,例如:

struct Names 
{char * name;
char * longname;} name;

Then:然后:

(aCPointer at: 0) copyCStringFromHeap. "answer [name]"
(aCPointer at: 1) copyCStringFromHeap. "answer [longname]"

For structs with char * it work nicely not tested with other C types.对于带有 char * 的结构,它可以很好地工作,没有用其他 C 类型进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM