1

I have earlier been able to call Swift methods using a function pointer from C, and providing the appropriate arguments because the calling convention was the same.

Unfortunately this no longer works. This is because Swift has added a "call context" argument that is passed in a separate register (r13) from the normal arguments. For regular method calls, this context is a pointer to self. See here for more info: https://github.com/apple/swift/blob/master/docs/ABIStabilityManifesto.md#calling-convention

So in order to call these methods, I need to be able to reliably set r13 to the appropriate value from C.

How can I do this in clang/llvm?

I do not find a way to declare a register variable to a specific register (gcc syntax for that does not work). So I have code like this:

void (*my_fp)(void *) = find_pointer();
void *instance = find_instance();
void *arg1 = whatever();
asm {
    mov r13, [instance]
}
my_fp(arg1);

It might or might not work - sometimes the compiler clobbers r13 immediately by using it for the function pointer. Also I guess it's not particularly safe to just write to that register without the compiler's consent.

Is there a reliable way to do this?

(By the way, I am not able to include the Swift runtime in my code, so I must be able to call from C.)

-1

a good, "semiofficial" approach can be found here:

https://forums.swift.org/t/best-way-to-call-a-swift-function-from-c/9829/3

(Quinn is by far the best apple programmer ever existed) :)

  • 1
    Hi and welcome RE.SE. Answers like yours are not seen favorably on StackExchange for one reason: link rot. It's very common that a link like yours goes stale and then your answer becomes useless (no matter how many upvotes it may have gathered at that point). Please include relevant portions of the approach linked either by explaining them in your own words or quoting relevant parts (without quoting excessively and actually infringing on the copyright of the linked resource). Nothing wrong with links, but your answer should be able to stand alone without the link. – 0xC0000022L Dec 2 '18 at 20:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.