Passing a quick pointer to a C function
Let's say I have a Swift structure named Foo
struct Foo
{
var a,b,c : Float
var d : Double
init()
{
a = 0
b = 0
c = 0
d = 0
}
}
Swift sizeof (Foo) prints 24 bytes, 4 bytes for Float fields, 8 for Double and 4 bytes for padding on arm64.
So I believe there is no Swift special magic with string alignment, and we can freely pass pointers to it to internal C functions to use things like NEON and Metal, since inline variables are unions, which currently cannot be directly included in Swift
Somehow when I try to get const void * to it (ConstUnsafePointer <()> in Swift) using
let a = Foo()
let b = &a
I am getting a nasty compiler error in the second expression
'Foo' is not convertible to '@lvalue inout $T1'
Am I missing something and this is by design?
UPDATED PART
Martn R, thanks for the answer! However, the whole situation is not very clear to me. My goal was to create a convenient wrapper for the Math stuff, so I wanted to implement @infix methods like multiply and hide all internal native materials behind C. In the case of Matrices, for example, this means we need to pull the ampersand straight from a = & b * & c because I haven't gotten from your answer and Docs if there is a way to get around this and get the starting point from memory in the implementation scope of the @infix method.
Like this:
@infix public func *(l: Mat4, r: Mat4) -> Mat4
{
var m = Mat4()
_internalMat4Multiply(&l, &r, &m)
}
_internalMat4Multiply is a void (void *, void *, void *) C method that does all calculations
source to share
There are two problems: you cannot take the address of a constant (defined with let
), and you can only pass the address of a variable to function parameters. Assuming your C function
void myFunc(const void *data);
then it would work:
var a = Foo()
myFunc(&a)
However, instead of making assumptions about identical alignment in C and Swift, you might be better off defining the structure in your API:
struct Foo {
float a;
float b;
float c;
double d;
};
void myFunc(const struct Foo *data);
and use this from Swift code:
var a = Foo(a: 0, b: 0, c: 0, d: 0)
myFunc(&a)
source to share