Implementing a template function to cast lambdas to function pointer with different calling convention in Visual C++

I want to create a template function that casts lambdas to function pointers of different calling conventions.

template<typename RetType, typename... Args>
auto fastcall_cast(LambdaType lambda) -> RetType(__fastcall *)(Args...)
{
    return static_cast<RetType(__fastcall *)(Args...)>(lambda);
}

int main() {
    auto pFunc = fastcall_cast([](int a, int b) -> int {
        return a + b;
    });

    // this is what I want to replicate without the boilerplate:
    auto pFunc2 = static_cast<int(__fastcall *)(int, int)>([](int a, int b) -> int {
        return a + b;
    });

};

I have been relying on this macro previously but I find it quite ugly as it requires an extra closing parenthesis in the end:

#define INLINE_HOOK(retnType, callingConv, ...) static_cast<retnType(callingConv*)(__VA_ARGS__)>([](__VA_ARGS__) [[msvc::forceinline]] -> retnType

WriteRelCall(0x4909BC, INLINE_HOOK(UInt32, __fastcall, BSAnimGroupSequence* anim)
{
    if (anim->textKeys->FindFirstByName("allowClampInLocomotion"))
        return NiControllerSequence::kCycle_Loop;
    return anim->cycleType;
}));

It is not possible to specify a calling convention directly inside a lambda in VC++ as it’ll simply ignore it with a warning stating warning C4229: anachronism used: modifiers on data are ignored. Apparently you need to cast it.

Ideally the template function does not require any explicit template arguments and is able to be deduced from the lambda itself.

Is this possible in Visual C++?

EDIT: For some more context, this is for writing hooks into a game during runtime. It needs specific calling conventions so that the hooks are compatible with the game’s native functions which are usually __thiscall. WriteRelCall takes the pointer value of the function, and replaces the x86 assembly in the game with the new function.

Here is the definition of WriteRelCall.

Full example of what I’m trying to do

23

Wit MSVC x86 target, first we need an arg forwarder different from std::forward:

template<typename targ>
[[msvc::intrinsic]]
constexpr decltype(auto) fast_fwd(std::type_identity_t<targ>& arg){
    /*if constexpr(std::is_reference_v<targ>
          or not std::is_trivial_v<targ>)
        return static_cast<targ&&>(varg);
    else*/ 
        return static_cast<targ>(varg);
};

This forwarder captures trivial arguments by value. On second thought, it should be a simple static cast. But the abstraction allows for later tweaks.

Next a detail only dirty template function:

template<auto lambda, typename R, typename ...A>
R __fastcall as_fast_impl(A ...v){
    return lambda(fast_fwd<A>(v)...);
};

Now a declare template variable with usless implementation:

template<auto lambda, typename fptr = decltype(+lambda)>
constexpr auto as_fast = nullptr;

Next specialize the real use case:

template<auto lambda, typename R, typename ...A>
auto constexpr as_fast<lambda, R(*)(A...)> = as_fast_impl<lambda, R, A...>;

The cast is ready. We can make fastcall pointers out of empty capture lambdas

auto fast_call_ptr = as_fast<
[](int,int)->int{
    return 0;
}>;

This is a C++20/C++23 solution. Aside from typos in my snippet, due to a now-resolved defect in std wording, some combinations compiler version and std version setting may reject lambda as NTTP. Otherwise, the code tries to optimize away copy/move of argument; but in general, if arguments are none trivial and none reference, copy/moves will be inferred into the fastcall wrapper. Moreover the lambda needs to have single none-generic (no [](auto...)), none-template(no []<A...>) function call operator.

2

You don’t need an explicit cast to convert a (non-capturing) lambda into a function pointer. The compiler can do that conversion implicitly for you when you assign the lambda to the pointer. Let it figure out the calling convention for you, eg:

int (__fastcall *pFunc)(int, int) = [](int a, int b) -> int { ... };
// or:
// int (__fastcall *pFunc)(int, int);
// pFunc = [](int a, int b) -> int { ... };
template <typename RetType, typename... Args>
void WriteRelCall(UInt32 jumpSrc, RetType (__fastcall *jumpTgt)(Args...))
{
    ...
}

WriteRelCall(0x4909BC, [](BSAnimGroupSequence* anim) -> UInt32 { ... });

See: how to specify vc11 lambda calling convention

If, for some reason, you do need an explicit conversion, you can simply use the unary + operator, eg:

+[](int a, int b) -> int { ... };
+[](BSAnimGroupSequence* anim) -> UInt32 { ... }

21

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật