【问题标题】:One function gives several results in swift一个函数可以快速给出几个结果
【发布时间】:2016-10-21 08:00:06
【问题描述】:

我在 Objective-C 中有一个我从 swift 调用的方法。它在 swift 2 中运行良好,但在 swift 3 中行为发生了变化。即使我发送相同的参数,它也会给我 3 个不同的结果。

有时它找不到 pfile,有时它在 pin 检查时失败,有时运行良好并给我 x509。

char* ParsePKCS12(unsigned char* pkcs12_path, unsigned char * pin) {
printf("PARSE PATH: %s\n", pkcs12_path);
printf("PASSWORD: %s\n", pin);

NSString *pfile = [NSString stringWithUTF8String:pkcs12_path];
FILE *fp;
PKCS12 *p12;
EVP_PKEY *pkey;
X509 *cert;

BIO *databio = BIO_new(BIO_s_mem());
STACK_OF(X509) *ca = NULL;

if([[NSFileManager defaultManager] fileExistsAtPath:pfile]) {
    NSLog(@"ok, pfile exists!");
} else {
    NSLog(@"error, pfile does not exists!");
    return "-1";
}
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
fp = fopen([pfile UTF8String], "rb");
p12 = d2i_PKCS12_fp(fp, NULL);
fclose (fp);
if (!p12) {
    fprintf(stderr, "Error reading PKCS#12 file\n");
    ERR_print_errors_fp(stderr);
    return "-1";
}

if (!PKCS12_parse(p12, (const char *)pin, &pkey, &cert, &ca)) { //Error at parsing or pin error
    fprintf(stderr, "Error parsing PKCS#12 file\n");
    ERR_print_errors_fp(stderr);
    ERR_print_errors(databio);
    return "-1";
}

BIO *bio = NULL;
char *pem = NULL;

if (NULL == cert) {
    //return NULL;
    return "-1";
}

bio = BIO_new(BIO_s_mem());
if (NULL == bio) {
    return "-1";
}

if (0 == PEM_write_bio_X509(bio, cert)) {
    BIO_free(bio);
    //return NULL;
}

pem = (char *) malloc(bio->num_write + 1);
if (NULL == pem) {
    BIO_free(bio);
    return "-1";
}

memset(pem, 0, bio->num_write + 1);
BIO_read(bio, pem, bio->num_write);
BIO_free(bio);

PKCS12_free(p12);

return pem;
}

我这样快速调用这段代码:

self.x509 = String(cString:ParsePKCS12(UnsafeMutablePointer<UInt8>(mutating: self.path),
                                           UnsafeMutablePointer<UInt8>(mutating: "123456"))!)

【问题讨论】:

    标签: ios objective-c c swift openssl


    【解决方案1】:

    您的电话

    self.x509 = String(cString:ParsePKCS12(UnsafeMutablePointer<UInt8>(mutating: self.path),
                                               UnsafeMutablePointer<UInt8>(mutating: "123456"))!)
    

    不能可靠地工作,因为在两者中

    UnsafeMutablePointer<UInt8>(mutating: someSwiftString)
    

    调用,编译器创建一个临时的 C 字符串表示 Swift 字符串并将其传递给函数。但是那个C弦 仅在UnsafeMutablePointer 构造函数返回之前有效,这意味着第二个 字符串转换可以覆盖第一个,或任何其他未定义的 行为。

    最简单的解决方案是将 C 函数更改为 采用常量 C 字符串(并使用默认签名):

    char* ParsePKCS12(const char * pkcs12_path, const char * pin)
    

    那你就可以简单地称呼它为

    self.x509 = String(cString: ParsePKCS12(self.path, "123456"))
    

    并且编译器会创建临时的 C 字符串,这些字符串在 ParsePKCS12()的来电。

    【讨论】:

      猜你喜欢
      • 2020-06-02
      • 1970-01-01
      • 2022-08-05
      • 2021-10-07
      • 1970-01-01
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多