From 6bcc263b41edf99ed70657b8b12a24a4bf183a99 Mon Sep 17 00:00:00 2001 From: Richard Berger Date: Fri, 28 Aug 2020 14:21:03 -0400 Subject: [PATCH] Ensure LAMMPS pointer is of type c_void_p Fixes segfaults caused by API change. The API change in lammps_open and lammps_open_no_mpi makes them return the LAMMPS pointer via their return value. However due to how ctypes operates, even if restype is specified to be c_void_p, the function returns an integer. Without the proper type of the pointer, calling functions without arglists would default to using 32bit integers to pass an argument, which cuts away parts of the 64bit pointer. Subsequently, resolving the truncated pointer in the library causes segfaults. This commit fixes the root cause. But it also highlights the need of specifying the arglists of all library functions. --- python/lammps.py | 6 +++--- unittest/python/python-numpy.py | 4 ++++ 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/python/lammps.py b/python/lammps.py index 64268bc345..f242ae1af6 100644 --- a/python/lammps.py +++ b/python/lammps.py @@ -340,7 +340,7 @@ class lammps(object): self.opened = 1 comm_ptr = self.MPI._addressof(comm) comm_val = MPI_Comm.from_address(comm_ptr) - self.lmp = self.lib.lammps_open(narg,cargs,comm_val,None) + self.lmp = c_void_p(self.lib.lammps_open(narg,cargs,comm_val,None)) else: if self.has_mpi4py and self.has_mpi_support: @@ -355,10 +355,10 @@ class lammps(object): cargs = (c_char_p*narg)(*cmdargs) self.lib.lammps_open_no_mpi.argtypes = [c_int, c_char_p*narg, \ c_void_p] - self.lmp = self.lib.lammps_open_no_mpi(narg,cargs,None) + self.lmp = c_void_p(self.lib.lammps_open_no_mpi(narg,cargs,None)) else: self.lib.lammps_open_no_mpi.argtypes = [c_int, c_char_p, c_void_p] - self.lmp = self.lib.lammps_open_no_mpi(0,None,None) + self.lmp = c_void_p(self.lib.lammps_open_no_mpi(0,None,None)) else: # magic to convert ptr to ctypes ptr diff --git a/unittest/python/python-numpy.py b/unittest/python/python-numpy.py index 2d961d630c..67dee454a1 100644 --- a/unittest/python/python-numpy.py +++ b/unittest/python/python-numpy.py @@ -1,5 +1,6 @@ import sys,os,unittest from lammps import lammps, LMP_STYLE_GLOBAL, LMP_STYLE_ATOM, LMP_TYPE_VECTOR, LMP_TYPE_SCALAR +from ctypes import c_void_p class PythonNumpy(unittest.TestCase): def setUp(self): @@ -11,6 +12,9 @@ class PythonNumpy(unittest.TestCase): def tearDown(self): del self.lmp + def testLammpsPointer(self): + self.assertEqual(type(self.lmp.lmp), c_void_p) + def testExtractCompute(self): self.lmp.command("region box block 0 2 0 2 0 2") self.lmp.command("create_box 1 box")