You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测DLL的#import导入?实现基于导入状态的条件编译

Hey there! The issue here is that #import doesn't automatically define a preprocessor symbol you can check, but we can work around that easily with a couple of straightforward steps. Here's how to set up conditional compilation based on whether the DLL was imported:


1. Explicitly Define a Macro When You Import the DLL

Whenever you use #import "testing.dll", add a custom preprocessor definition right after it. This will act as our flag for other files to check:

// X.cpp
#import "testing.dll"
#define TESTING_DLL_IMPORTED  // This is our custom flag
#include "A.h"

2. Check for the Macro in Your Header File

In A.h, use #ifdef to branch your code based on whether the flag exists:

// A.h
#ifdef TESTING_DLL_IMPORTED
    // Code that uses functionality from testing.dll
    // (e.g., COM interfaces or types from the imported type library)
    void PerformOperation() {
        // Use testing.dll-specific logic here
    }
#else
    // Fallback logic when testing.dll isn't available/imported
    void PerformOperation() {
        // Alternative implementation
    }
#endif

Alternative: Use the Auto-Generated TLH Include Guard

If you don't want to add an explicit #define, you can check the include guard that MSVC automatically creates for the generated .tlh file. The guard follows the pattern _<TYPE_LIBRARY_NAME>_TLH_ (uppercase, with underscores replacing any non-alphanumeric characters).

For example, if your testing.dll's internal type library is named "Testing", the guard would be _TESTING_TLH_:

// A.h
#ifdef _TESTING_TLH_
    // Use testing.dll code
#else
    // Fallback logic
#endif

Heads up: This is specific to MSVC and depends on the type library's internal name (which might not match the DLL filename), so the explicit macro approach is more reliable and portable.

Why This Works

The #import directive generates .tlh and .tli files but doesn't include a standard checkable macro. By adding our own #define, we create a clear, intentional flag that other parts of the code can use. Plus, #import is idempotent—even if you import the DLL in multiple files, the compiler will skip reprocessing it after the first time, so redefining the macro is safe (no warnings unless you have strict preprocessor settings enabled).

内容的提问来源于stack exchange,提问作者Mark Ransom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:11:04