如何将 Swift 字符串传递给 c 函数? [英] How to pass a Swift string to a c function?

查看:34
本文介绍了如何将 Swift 字符串传递给 c 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将字符串从 swift 传递到用 c 编写的函数时遇到了严重的问题.

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)

c 函数如下所示:

void initSocket(char *address, int port);

我收到错误:无法将Void"类型的表达式转换为CMutablePointer"类型

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.

推荐答案

Swift CStrings 与 C 常量字符串无缝协作,所以使用

Swift CStrings work seamlessly with C constant strings, so use

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

而不是 char* 参数,并将您的 address 变量声明为 CString:

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

var address: CString = "192.168.1.2";

这篇关于如何将 Swift 字符串传递给 c 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆