How to make C (P/invoke) code called from C# “Thread-safe”

后端 未结 4 710
长情又很酷
长情又很酷 2021-02-08 06:43

I have some simple C-code which uses a single global-variable. Obviously this is not thread-safe, so when I call it from multiple threads in C# using P/invoke, things screw up.

4条回答
  •  遇见更好的自我
    2021-02-08 06:52

    The good news, you can create a __declspec(naked) function as a member of C++ (non-CLI) class:

    class A {
        int n;
    public:
        A() { n = 0; }
        void f(int n1, int n2);
    };
    
    __declspec(naked) void A::f(int n1, int n2)
    {
        n++;
    }
    

    The bad news, you will need COM to be able to use such class. That's right: asm wrapped in C++, wrapped in COM, wrapped in RCW, wrapped in CLR...

提交回复
热议问题