How to pass a Swift string to a c function?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-10 14:53:45

问题


I am having serious trouble passing a string from swift, to a function written in c.

I'm trying to do this in my swift code

var address = "192.168.1.2"
var port = 8888

initSocket(address, port)

The c function looks like this:

void initSocket(char *address, int port);

Im getting the error: Cannot convert the expression's of type 'Void' to type 'CMutablePointer'

I can't seem to find a solution that works.


回答1:


Swift CStrings work seamlessly with C constant strings, so use

void initSocket(const char *address, int port);

instead of char* argument, and declare your address variable as CString:

var address: CString = "192.168.1.2";


来源:https://stackoverflow.com/questions/25378954/how-to-pass-a-swift-string-to-a-c-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!