tinysun212 / swift-windows

Swift compiler for Cygwin, MSVC, MinGW. Full development environment can be downloaded from the Swift for Windows.
http://SwiftForWindows.github.io
Apache License 2.0
331 stars 30 forks source link

Calling C functions from Swift #3

Closed ianba3 closed 8 years ago

ianba3 commented 8 years ago

I would like to call some C functions from Swift. I am trying to use a Bridging-Header.h to accomplish this. However, when I try to compile:

swiftc -c SwiftTest.swift -import-objc-header Bridging-Header.h 

I get an error:

<unknown>:0: error: failed to import bridging header 'Bridging-Header.h'

SwiftTest.swift contains: hello_c("World".cStringUsingEncoding(NSUTF8StringEncoding))

Bridging-Header.h is empty, just to make sure there's nothing offending in it.

However, Bridging-Header.h previously contained: #import "SwiftAPI.h"

And SwiftAPI.h contains: void hello_c(const char * name);

With a corresponding SwiftAPI.c:

    #include "SwiftAPI.h"
    #include <stdio.h>
    void hello_c(const char * name) {
        printf("Hello %s in C\n", name);
    }

Is there a better way to do this? Is there a way to get more detailed error messages?

Thanks a lot!

tinysun212 commented 8 years ago

With same SwiftAPI.h and SwiftAPI.c of yours,

$ cat SwiftTest.swift
hello_c("World")

$ gcc -c -o SwiftAPI.o SwiftAPI.c

$ swiftc -import-objc-header SwiftAPI.h SwiftTest.swift SwiftAPI.o -o SwiftTest.exe

$ ./SwiftTest
Hello World in C

Bridging-Header.h is not used.

ianba3 commented 8 years ago

Thanks a lot. That worked!