I'm using D and interfacing with some C libraries. As a result I have to convert D arrays to pointers for C (ex. short*). Currently I just cast them like this:
我使用D,并与一些C库交互。因此,我必须将D数组转换为C (ex. short*)的指针。现在我就这样把它们扔了:
int[] dArray = [0, 1, 2, 3, 4];
myCFunction(cast(int*) dArray);
Is this unsafe? I tried to do:
这是不安全的吗?我想做的事:
myCFunction(&dArray);
But doing that gives the function an int[]* instead of int*. I see that in C++ some people take the first element like this:
但是这样做给了函数一个int[]*而不是int*。我在c++中看到一些人使用第一个元素:
myCFunction(&dArray[0]);
But wouldn't that pointer only point to the first element? I am new to pointers and references as I have come from the world of Java.
但是那个指针不是指向第一个元素吗?我是来自Java世界的新指针和引用。
How would I convert an array to a pointer so I can pass it to a C function?
我如何将数组转换为一个指针,这样我就可以把它传递给C函数?
1 个解决方案
#1
11
In D, an array is actually (conceptually) this:
在D中,数组实际上(概念上)是这样的:
struct {
size_t length;
void* ptr;
};
The usual way of getting a pointer from an array is to use the .ptr field. In your case: myCFunction(dArray.ptr);
从数组中获取指针的通常方法是使用.ptr字段。在你的例子:myCFunction(dArray.ptr);
But wouldn't that pointer only point to the first element
但是这个指针不会指向第一个元素。
Because the elements are stored contiguously in memory, a pointer to the first element is all we need. We just add an offset to that pointer if we want to get the addresses of other elements.
因为元素是在内存中连续存储的,所以我们只需要一个指向第一个元素的指针。如果我们想要得到其他元素的地址,我们只需向该指针添加一个偏移量。
One other point: usually if a C function wants an array pointer, it also has an argument for the array length. In most cases you can give it dArray.length
, but sometimes it's actually asking for the size in bytes, rather than the number of elements.
另一个要点:通常如果C函数想要一个数组指针,它也有一个数组长度的参数。在大多数情况下,你可以给它dArray。长度,但有时它实际上要求的是字节的大小,而不是元素的数量。
#1
11
In D, an array is actually (conceptually) this:
在D中,数组实际上(概念上)是这样的:
struct {
size_t length;
void* ptr;
};
The usual way of getting a pointer from an array is to use the .ptr field. In your case: myCFunction(dArray.ptr);
从数组中获取指针的通常方法是使用.ptr字段。在你的例子:myCFunction(dArray.ptr);
But wouldn't that pointer only point to the first element
但是这个指针不会指向第一个元素。
Because the elements are stored contiguously in memory, a pointer to the first element is all we need. We just add an offset to that pointer if we want to get the addresses of other elements.
因为元素是在内存中连续存储的,所以我们只需要一个指向第一个元素的指针。如果我们想要得到其他元素的地址,我们只需向该指针添加一个偏移量。
One other point: usually if a C function wants an array pointer, it also has an argument for the array length. In most cases you can give it dArray.length
, but sometimes it's actually asking for the size in bytes, rather than the number of elements.
另一个要点:通常如果C函数想要一个数组指针,它也有一个数组长度的参数。在大多数情况下,你可以给它dArray。长度,但有时它实际上要求的是字节的大小,而不是元素的数量。