簡體   English   中英

從帶有ctypes的C ++函數返回字符串會產生大int,而不是char指針

[英]Returning string from C++ function with ctypes gives large int, not char pointer

我正在嘗試使用python中的ctypes從dll調用C ++函數。 我當前的問題是該函數似乎返回一個較大的int,無論是正數還是負數,而不是我期望的char指針。 如果我將int轉換為c_char_p並對其調用.value,它每次都會殺死我的內核。 我在整個網站和文檔中都查看過,無法解決。 我在該站點上看到的許多東西甚至給我帶來了錯誤,例如將字符串傳遞給ctypes opjects和function時,它們應該是字節對象或類似對象。 下面是我的c ++代碼,它已轉換為dll,以及我用來從dll調用函數的python代碼。 如果有人可以幫助我,那太好了。 SaySomething是有問題的功能。 謝謝。

TestLibrary.h

#pragma once

#ifdef TESTLIBRARY_EXPORTS
#define TESTLIBRARY_API __declspec(dllexport)
#else
#define TESTLIBRARY_API __declspec(dllexport)
#endif

#include <windows.h>
#include <cstring>

#ifdef __cplusplus
extern "C"
{
#endif

    TESTLIBRARY_API char* SaySomething(const char* phrase);

#ifdef __cplusplus
};
#endif

TestLibrary.cpp

#include "stdafx.h"
#include "TestLibrary.h"
#include <iostream>

TESTLIBRARY_API char* SaySomething(const char* phrase)
{
    char* p = new char [100];
    p = "string something";
    return p;
}

tester2.py

import ctypes

dbl = ctypes.c_double
pChar = ctypes.c_char_p
pVoid = ctypes.c_void_p

libName = (r"D:\Documents\Coding Stuff\Visual Studio 2017\Projects\TestLibrary"
           r"Solution\x64\Debug\TestLibrary.dll")
x = ctypes.windll.LoadLibrary(libName)

x.SaySomething.argtypes = [pChar]
x.SaySomething.restypes = pChar

phrase = b"Hi"
phrase = pChar(phrase)

res = x.SaySomething(phrase)

雖然可以使API發揮您的作用,但當前會發生內存泄漏。 更好的解決方案是讓Python為結果分配和管理內存。

我還修復了注釋中提到的dllimport ,並在.cpp文件中定義了TESTLIBRARY_EXPORTS ,以便該函數可以從DLL中導出。 restype也已修復。

TesterLibrary.h

#pragma once

#ifdef TESTLIBRARY_EXPORTS
#define TESTLIBRARY_API __declspec(dllexport)
#else
#define TESTLIBRARY_API __declspec(dllimport)
#endif

#define WIN32_LEAN_AND_MEAN
#include <windows.h>

#ifdef __cplusplus
extern "C" {
#endif

TESTLIBRARY_API char* SaySomething(const char* phrase, char* result, size_t resultMaxLength);

#ifdef __cplusplus
}
#endif

TesterLibrary.cpp

#define TESTLIBRARY_EXPORTS
#include "TestLibrary.h"
#include <stdio.h>

TESTLIBRARY_API char* SaySomething(const char* phrase, char* result, size_t resultMaxLength)
{
    _snprintf_s(result,resultMaxLength,_TRUNCATE,"Decorated <%s>",phrase);
    return result;
}

tester2.py

import ctypes

libName = (r"TestLibrary.dll")
x = ctypes.CDLL(libName)

x.SaySomething.argtypes = [ctypes.c_char_p,ctypes.c_char_p,ctypes.c_size_t]
x.SaySomething.restype = ctypes.c_char_p

phrase = b"Hi"
result = ctypes.create_string_buffer(100)
res = x.SaySomething(phrase,result,ctypes.sizeof(result))
print(res)
print(result.value)

產量

b'Decorated <Hi>'
b'Decorated <Hi>'

當沒有更多引用時,Python將自動釋放result緩沖區。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM