Skip to content

Cannot marshal 'parameter #1': Pointers cannot reference marshaled structures. Use ByRef instead. #350

@ujos

Description

@ujos

Cannot pass the structure via pointer if structure contains a bool variable. Code compiles but MarshalDirectiveException exception is thrown during runtime.

Steps to reproduce

  1. Download and extract test.zip
  2. Run reproduce.cmd

Expected that test.exe prints nothing.

In fact the output is:

Unhandled Exception: System.Runtime.InteropServices.MarshalDirectiveException: Cannot marshal 'parameter #1': Pointers cannot reference marshaled structures.  Use ByRef instead.
   at TestLib.DLL.foo(X* x)
   at Program.<Main>$(String[] args)

In case if I replace pointer with ref, the code works.

Version

 (master) test $ ClangSharpPInvokeGenerator --version
ClangSharp P/Invoke Binding Generator version 14.0.0
  clang version 14.0.0
  clangsharp version 14.0.0

Archive content

// test_lib.h

#include <stdbool.h>

#ifdef __cplusplus
extern "C"
{
#endif

struct X 
{
    bool Flag;
};

void __declspec(dllexport) foo(struct X const* x);

#ifdef __cplusplus
}
#endif
// test_lib.cpp

#include "test_lib.h"

void foo(X const*)
{
}

Following is config file for ClangSharpPInvokeGenerator

--file
test_lib.h

--namespace
TestLib

--headerFile
pinvoke-header.txt

--output
test_lib.cs

--language
c++

--methodClassName
DLL

--libraryPath
test_lib.dll

--config
compatible-codegen

Following is a C# test program:

using ClangSharp.Interop;

unsafe
{
    var x = new TestLib.X();

    TestLib.DLL.foo(&x);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions