简体   繁体   中英

VBA kernel32 InterlockedIncrement not available in 64 bit host, what should I do?

I'm in the process of upgrading some code from 32 to 64 bit VBA. It uses the InterlockedIncrement function:

Private Declare PtrSafe Function InterlockedIncrement Lib "kernel32" (ByRef Addend As Long) As Long

This was formerly exported by kernel32 but only for x86 callers. Running from 64-bit Excel it's not so simple, I get a " Can't find DLL entry point InterlockedIncrement in kernel32 " error - here's the reason I found:

On 64 bit windows these are not real functions [...] they are compiler intrinsics instead. The code that is P/Invoking that function should be using the Interlocked managed class

What's a good alternative/ can I fix this?


For context, I'm updating the code from this answer on SO where InterlockedIncrement & InterlockedDecrement are used to do COM reference counting. Now I understand these Interlocked functions are atomic operations which is important for multithreading, however since VBA runs in a single threaded apartment do I even need to bother? Is this.refCount = this.refCount + 1 sufficient? The code is slightly above my head so I can't be 100% certain that I won't introduce a bug by forgetting about these functions but let me know either way.

Single threaded drop-in replacements

Private Function InterlockedIncrement(ByRef Addend As Long) As Long
    Addend = Addend + 1
    InterlockedIncrement = Addend
End Function

Private Function InterlockedDecrement(ByRef Addend As Long) As Long
    Addend = Addend - 1
    InterlockedDecrement = Addend
End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM