Skip to content

Commit

Permalink
Add a function strings_to_ctypes_array to convert a sequence of strin…
Browse files Browse the repository at this point in the history
…gs into a ctypes array
  • Loading branch information
seisman committed Mar 23, 2024
1 parent 32e3cb3 commit 32c97d5
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 9 deletions.
28 changes: 28 additions & 0 deletions pygmt/clib/conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
Functions to convert data types into ctypes friendly formats.
"""

import ctypes as ctp
import warnings
from collections.abc import Sequence

import numpy as np
from pygmt.exceptions import GMTInvalidInput
Expand Down Expand Up @@ -280,6 +282,32 @@ def kwargs_to_ctypes_array(argument, kwargs, dtype):
return None


def strings_to_ctypes_array(strings: Sequence[str]):
"""
Convert a sequence (e.g., a list) of strings into a ctypes array.
Parameters
----------
strings
A sequence of strings.
Returns
-------
ctypes_array
A ctypes array of strings.
Examples
--------
>>> strings = ["first", "second", "third"]
>>> ctypes_array = strings_to_ctypes_array(strings)
>>> type(ctypes_array)
<class 'pygmt.clib.conversion.c_char_p_Array_3'>
>>> [s.decode() for s in ctypes_array]
['first', 'second', 'third']
"""
return (ctp.c_char_p * len(strings))(*[s.encode() for s in strings])


def array_to_datetime(array):
"""
Convert a 1-D datetime array from various types into numpy.datetime64.
Expand Down
14 changes: 5 additions & 9 deletions pygmt/clib/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
as_c_contiguous,
dataarray_to_matrix,
kwargs_to_ctypes_array,
strings_to_ctypes_array,
vectors_to_arrays,
)
from pygmt.clib.loading import load_libgmt
Expand Down Expand Up @@ -890,13 +891,9 @@ def put_vector(self, dataset, column, vector):

gmt_type = self._check_dtype_and_dim(vector, ndim=1)
if gmt_type in (self["GMT_TEXT"], self["GMT_DATETIME"]):
vector_pointer = (ctp.c_char_p * len(vector))()
if gmt_type == self["GMT_DATETIME"]:
vector_pointer[:] = np.char.encode(
np.datetime_as_string(array_to_datetime(vector))
)
else:
vector_pointer[:] = np.char.encode(vector)
vector = np.datetime_as_string(array_to_datetime(vector))
vector_pointer = strings_to_ctypes_array(vector)
else:
vector_pointer = vector.ctypes.data_as(ctp.c_void_p)
status = c_put_vector(
Expand Down Expand Up @@ -953,13 +950,12 @@ def put_strings(self, dataset, family, strings):
restype=ctp.c_int,
)

strings_pointer = (ctp.c_char_p * len(strings))()
strings_pointer[:] = np.char.encode(strings)

family_int = self._parse_constant(
family, valid=FAMILIES, valid_modifiers=METHODS
)

strings_pointer = strings_to_ctypes_array(strings)

status = c_put_strings(
self.session_pointer, family_int, dataset, strings_pointer
)
Expand Down

0 comments on commit 32c97d5

Please sign in to comment.