GVKun编程网logo

使用ctypes和Python将字符串传递给Fortran DLL(python ctypes 字符串)

16

想了解使用ctypes和Python将字符串传递给FortranDLL的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于pythonctypes字符串的相关问题,此外,我们还将为您介绍关于ba

想了解使用ctypes和Python将字符串传递给Fortran DLL的新动态吗?本文将为您提供详细的信息,我们还将为您解答关于python ctypes 字符串的相关问题,此外,我们还将为您介绍关于bash – 将字符串列表传递给for循环、Python ctypes:传递一个字符串数组、python TypeError: unsupported operand type(s) for +: ''geoprocessing value object'' and ...、Python TypeError:传递给对象的非空格式字符串__format__的新知识。

本文目录一览:

使用ctypes和Python将字符串传递给Fortran DLL(python ctypes 字符串)

使用ctypes和Python将字符串传递给Fortran DLL(python ctypes 字符串)

我正在尝试使用ctypes在Python2.7中加载DLL。DLL是使用Fortran编写的,并且其中包含多个子例程。我能够成功设置几个导出的函数,long并将这些函数和double指针作为参数。

import ctypes as C
import numpy as np

dll = C.windll.LoadLibrary('C:\\Temp\\program.dll')
_cp_from_t = getattr(dll,"CP_FROM_T")
_cp_from_t.restype = C.c_double
_cp_from_t.argtypes = [C.POINTER(C.c_longdouble),np.ctypeslib.ndpointer(C.c_longdouble)]

# Mixture Rgas function
_mix_r = getattr(dll,"MIX_R")
_mix_r.restype = C.c_double
_mix_r.argtypes = [np.ctypeslib.ndpointer(dtype=C.c_longdouble)]

def cp_from_t(composition,temp):
    """ Calculates Cp in BTU/lb/R given a fuel composition and temperature.

    :param composition: numpy array containing fuel composition
    :param temp: temperature of fuel
    :return: Cp
    :rtype : float
    """
    return _cp_from_t(C.byref(C.c_double(temp)),composition)

def mix_r(composition):
    """Return the gas constant for a given composition.
    :rtype : float
    :param composition: numpy array containing fuel composition
    """
    return _mix_r(composition)

# At this point,I can just pass a numpy array as the composition and I can get the 
# calculated values without a problem
comps = np.array([0,12.0,23.0,33.0,10,5.0])
temp = 900.0

cp = cp_from_t(comps,temp)
rgas = mix_r(comps)

到现在为止还挺好。

当我尝试调用
另一个Function2需要一些字符串作为输入的子例程时,就会出现问题。字符串都是固定长度(255),并且它们还会要求每个字符串参数的长度。

该功能在Fortran中实现如下:

Subroutine FUNCTION2(localBasePath,localTempPath,InputFileName,Model,DataArray,ErrCode)
!DEC$ ATTRIBUTES STDCALL,REFERENCE,ALIAS:'FUNCTION2',DLLEXPORT :: FUNCTION2
Implicit None
Character *255 localBasePath,InputFileName
Integer   *4  Model(20),ErrCode(20)
Real      *8  DataArray(900)

Python中的函数原型设置如下

function2 = getattr(dll,'FUNCTION2')
function2.argtypes = [C.POINTER(C.c_char_p),C.c_long,C.POINTER(C.c_char_p),np.ctypeslib.ndpointer(C.c_long,flags='F_CONTIGUOUS'),np.ctypeslib.ndpointer(C.c_double,flags='F_CONTIGUOUS')]

我称它为:

base_path = "D:\\Users\\xxxxxxx\\Documents\\xxxxx\\".ljust(255)
temp_path = "D:\\Users\\xxxxxxx\\Documents\\xxxxx\\temp".ljust(255)
inp_file = "inp.txt".ljust(255)

function2(C.byref(C.c_char_p(base_path)),C.c_long(len(base_path)),C.byref(C.c_char_p(temp_dir)),C.c_long(len(temp_dir))),C.byref(C.c_char_p(inp_file)),C.c_long(len(inp_file)),model_array,data_array,error_array)

字符串本质上是路径。该函数Function2无法识别路径,并在错误消息的末尾显示一些不可读的字符,例如:

forrtl: severe (43): file name specification error,unit 16,D:\Users\xxxxxxx\Documents\xxxxx\ωa

我想要的功能是D:\Users\xxxxxxx\Documents\xxxxx\。显然,字符串传递不正确。

我读过Python使用NULL终止的字符串。将字符串传递到Fortran dll时会出现问题吗?如果是这样,我该如何解决?

有什么建议吗?

bash – 将字符串列表传递给for循环

bash – 将字符串列表传递给for循环

如何在bash中传递列表?

我试过了

echo "some
different
lines
" | for i ; do 
  echo do something with $i; 
done

但这不起作用.我也试图找到与男人的解释,但没有男人

编辑:

我知道,我可以使用while,但我想我曾经看过一个解决方案,因为他们没有定义变量,但可以在循环中使用它

解决方法

这可能有用,但我不推荐它:

echo "some
different
lines
" | for i in $(cat) ; do
    ...
done

$(cat)将扩展stdin上的所有内容,但如果echo的其中一行包含空格,则会认为这是两个单词.所以最终可能会破裂.

如果要在循环中处理单词列表,则更好:

a=($(echo "some
different
lines
"))
for i in "${a[@]}"; do
    ...
done

说明:a =(…)声明一个数组. $(cmd …)扩展为命令的输出.它仍然容易受到空白的影响,但如果你引用得当,这可以修复.

“${a [@]}”扩展为数组中正确引用的元素列表.

注意:for是一个内置命令.请使用帮助(在bash中).

Python ctypes:传递一个字符串数组

Python ctypes:传递一个字符串数组

我在 Python 2.7中有一个字符串数组,我想通过ctypes传递给C函数:

unsigned int SetParams(unsigned int count,const char **params)

所以我可以在python中定义参数:

import ctypes as ct
lib = ct.cdll.LoadLibrary(''...'')
lib.SetParams.restype  = ct.c_uint
lib.SetParams.argtypes = [ct.c_uint,ct.POINTER(ct.c_char_p)]

但是现在当我在Python函数中给出一组参数时,我想在上面的库调用中使用它,我该如何实际调用它?我在想这样的事情:

def setParameters(strParamList):
    numParams    = len(strParamList)
    strArrayType = ct.c_char_p * numParams
    strArray     = strArrayType()
    for i,param in enumerate(strParamList):
        strArray[i] = param
    lib.SetParams(numParams,strArray)

我刚开始使用ctypes并想知道是否有更自动化的方法来执行此操作?赋值strArray [i] = param实际上是重新分配的吗?如果是这样,这似乎相当昂贵 – 有没有办法这样做只是将字符串指针指向Python分配的缓冲区,或者它们不是以NULL结尾?

更新我确实查看了几个相关的问题,但找不到直接处理相同问题的问题.非常感谢你

解决方法

你没想错.该代码有效.打电话,例如:

setParameters([''abc'',''def'',''ghi''])

我没有查看源代码,但Python 2.7(32位)上的ctypes确实传递了内部Python缓冲区(通过修改C函数中传递的字符串并在Python调用后打印它进行测试),这就是为什么你应该只将Python字符串传递给带有const char *的函数,或者至少知道不修改字符串的函数.由于Python字符串是不可变的,因此在C下写入它们是禁止的.使用ctypes.create_string_buffer创建一个可写字符串以传递给非const char *.

python TypeError: unsupported operand type(s) for +: ''geoprocessing value object'' and ...

python TypeError: unsupported operand type(s) for +: ''geoprocessing value object'' and ...

TypeError: unsupported operand type(s) for +: ''geoprocessing value object'' and ''str'' 
 if self.params[0].value:
        mypath=self.params[0].value #
        cpath=mypath+os.sep+dataset
        arcpy.env.workspace =cpath
修改如下:
 if self.params[0].value:
        mypath=str(self.params[0].value) #
        cpath=mypath+os.sep+dataset
        arcpy.env.workspace =cpath

 

Python TypeError:传递给对象的非空格式字符串__format__

Python TypeError:传递给对象的非空格式字符串__format__

我最近遇到了TypeError异常,发现它很难调试。我最终将其简化为这个小测试用例:

>>> "{:20}".format(b"hi")
Traceback (most recent call last):
  File "<stdin>",line 1,in <module>
TypeError: non-empty format string passed to object.__format__

无论如何,这对我来说不是很明显。我的代码的解决方法是将字节字符串解码为unicode:

 >>> "{:20}".format(b"hi".decode("ascii"))
 'hi                  '

此异常的含义是什么?有没有一种方法可以使它更清晰?

关于使用ctypes和Python将字符串传递给Fortran DLLpython ctypes 字符串的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于bash – 将字符串列表传递给for循环、Python ctypes:传递一个字符串数组、python TypeError: unsupported operand type(s) for +: ''geoprocessing value object'' and ...、Python TypeError:传递给对象的非空格式字符串__format__等相关知识的信息别忘了在本站进行查找喔。

本文标签: