在 C 程序中调用 Python 个函数

Calling Python functions in C program

我想在C程序中调用一个python函数实现SHA256加密。有人可以帮助我完成这项工作吗?或者有人可以给我一个在 C 中调用 Python 函数的例子吗?

谢谢!

对 Python 脚本进行 shell 处理,虽然它可以工作,但非常 hacky,不推荐。正如@JohnBollinger 在评论中提到的,您的 Python 解释器几乎肯定会使用 C 库进行哈希处理。因此,您将有一个 C 程序调用一个 Python 函数,该函数调用一个 C 函数。很迂回。

您最好使用可用于 C 的标准 TLS 库之一,例如 openssl 和 mbedTLS。它们的文档可在线获取(请参阅 here)。

这是一个使用 mbedTLS 的示例:

#include <stdio.h>
#include <sys/types.h>

#include <mbedtls/md.h>

int hashMe(const unsigned char *data, size_t size) {
    int ret;
    mbedtls_md_context_t ctx;
    unsigned char output[32];

    mbedtls_md_init(&ctx);
    ret=mbedtls_md_setup(
        &ctx,
        mbedtls_md_info_from_type(MBEDTLS_MD_SHA256),
        0 // Indicates that we're doing simple hashing and not an HMAC
    );
    if ( ret != 0 ) {
        return ret;
    }

    mbedtls_md_starts(&ctx);
    mbedtls_md_update(&ctx,data,size); // Call this multiple times for each chunk of data you want to hash.
    mbedtls_md_finish(&ctx,output);
    mbedtls_md_free(&ctx);

    printf("The hash is: ");
    for (unsigned int k=0; k<sizeof(output); k++) {
        printf("%02x ", output[k]);
    }
    printf("\n");

    return 0;
}