Semaphore or SemmaphoreSlim not working in Linux with pinvoke

mahia10 1 Reputation point
2022-08-26T03:44:07.007+00:00

Hi,

I am trying to create a .NET standard wrapper which calls the originally implemented API methods from C++ library. So, in my C++ library there is a method which takes one of the parameter is Unix type Semaphore which is sem_t * and I need to call that API method from .NET standard wrapper code which I am using initially "Semaphore" which is giving Exception like System.InvalidOperationException: Type 'System.Threading.Semaphore has a ComVisible(false) parent 'System.threading.WaitHandle' in its hierarchy, therefore Query Interface calls for I Dispatch or class interfaces are disallowed."

I found some where in documentation that "Semaphore" uses COM Win32 object, so I used passed "SemmaphoreSlim" as an argument to API method instead of "Semaphore", this time it worked fine in Windows, but giving an exception in Linux "System.Runtime.InteropServices.MarshalDirectiveException: Cannot marshal 'parameter #2': Invalid managed/unmanaged type combination (Interfaces must be paired with Interface)."

So is there any way to pass Semaphore using pinvoke by marshaling it?

please let me know.

Environment is .NET Standard 2.0 and .NET core 3.1

C++ method

void myAsyccSemaphore(sem_t * event, int eventType)

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,368 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,234 questions
.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,119 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 55,601 Reputation points
    2022-08-26T14:28:39.21+00:00

    You can not a .net implementation of Semphore as a substitute for the posix one. Using pinvoke, and dllimport you can call shmget() to create posix semaphore.

    https://man7.org/linux/man-pages/man7/sem_overview.7.html

    0 comments No comments