Skip to content

Commit

Permalink
Use custom strdup to avoid problems on Windows
Browse files Browse the repository at this point in the history
  • Loading branch information
fangerer committed Mar 22, 2022
1 parent 414386e commit 3183d23
Showing 1 changed file with 24 additions and 3 deletions.
27 changes: 24 additions & 3 deletions test/test_capsule.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,22 @@

class CapsuleTemplate(DefaultExtensionTemplate):

def DEFINE_strdup(self):
return """
#include <string.h>
static char *strdup0(const char *s)
{
size_t n = strlen(s) + 1;
char *copy = (char *) malloc(n * sizeof(char));
if (copy == NULL) {
return NULL;
}
strncpy(copy, s, n);
return copy;
}
"""

def DEFINE_SomeObject(self):
return """
#include <string.h>
Expand Down Expand Up @@ -161,6 +177,7 @@ def test_capsule_getter_and_setter(self):
mod = self.make_module("""
#include <string.h>
@DEFINE_strdup
@DEFINE_SomeObject
@DEFINE_Capsule_New
@DEFINE_Capsule_GetPointer
Expand Down Expand Up @@ -260,7 +277,7 @@ def test_capsule_getter_and_setter(self):
free((void *) old_name);
}
char *name_copy = strdup(name);
char *name_copy = strdup0(name);
if (name_copy == NULL) {
HPyErr_SetString(ctx, ctx->h_MemoryError, "out of memory");
return HPy_NULL;
Expand Down Expand Up @@ -406,9 +423,13 @@ def test_capsule_new_with_destructor(self):

class TestHPyCapsuleLegacy(HPyTest):

ExtensionTemplate = CapsuleTemplate

def test_legacy_capsule_compat(self):
import pytest
mod = self.make_module("""
@DEFINE_strdup
#include <Python.h>
#include <string.h>
Expand All @@ -417,7 +438,7 @@ def test_legacy_capsule_compat(self):
static void legacy_destructor(PyObject *capsule)
{
/* We need to use C lib 'free' because the string was
created with 'strdup'. */
created with 'strdup0'. */
free((void *) PyCapsule_GetName(capsule));
}
Expand All @@ -426,7 +447,7 @@ def test_legacy_capsule_compat(self):
{
HPy_ssize_t n;
const char *name = HPyUnicode_AsUTF8AndSize(ctx, arg, &n);
char *name_copy = strdup(name);
char *name_copy = strdup0(name);
if (name_copy == NULL) {
HPyErr_SetString(ctx, ctx->h_MemoryError, "out of memory");
return HPy_NULL;
Expand Down

0 comments on commit 3183d23

Please sign in to comment.